diff options
Diffstat (limited to 'public/fd_printf.html')
-rw-r--r-- | public/fd_printf.html | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/public/fd_printf.html b/public/fd_printf.html new file mode 100644 index 0000000..f875078 --- /dev/null +++ b/public/fd_printf.html @@ -0,0 +1,47 @@ +<!DOCTYPE html> +<html lang="en"> +<head> + <meta charset="utf-8"> + <title>`dprintf`: print formatted text directly to a file descriptor — Luke Shumaker</title> + <link rel="stylesheet" type="text/css" href="assets/style.css"> +</head> +<body> +<header><a href="/">Luke Shumaker</a> » <a href=/blog>blog</a> » fd_printf</header> +<article> +<h1 id="dprintf-print-formatted-text-directly-to-a-file-descriptor"><code>dprintf</code>: print formatted text directly to a file descriptor</h1> +<p>This already existed as <code>dprintf(3)</code>. I now feel stupid for having Implemented <code>fd_printf</code>.</p> +<p>The original post is as follows:</p> +<hr /> +<p>I wrote this while debugging some code, and thought it might be useful to others:</p> +<pre><code>#define _GNU_SOURCE /* vasprintf() */ +#include <stdarg.h> /* va_start()/va_end() */ +#include <stdio.h> /* vasprintf() */ +#include <stdlib.h> /* free() */ +#include <unistd.h> /* write() */ + +int +fd_printf(int fd, const char *format, ...) +{ + va_list arg; + int len; + char *str; + + va_start(arg, format); + len = vasprintf(&str, format, arg); + va_end(arg); + + write(fd, str, len); + + free(str); + return len; +}</code></pre> +<p>It is a version of <code>printf</code> that prints to a file descriptor—where <code>fprintf</code> prints to a <code>FILE*</code> data structure.</p> +<p>The appeal of this is that <code>FILE*</code> I/O is buffered—which means mixing it with raw file descriptor I/O is going to produce weird results.</p> + +</article> +<footer> +<p>The content of this page is Copyright © 2013 <a href="mailto:lukeshu@sbcglobal.net">Luke Shumaker</a>.</p> +<p>This page is licensed under the <a href="http://www.wtfpl.net/txt/copying/">WTFPL-2</a> license.</p> +</footer> +</body> +</html> |