summaryrefslogtreecommitdiff
path: root/public/fd_printf.html
blob: 2bc55a4a96dad62175f79ef50295d9c9370984dd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>`dprintf`: print formatted text directly to a file descriptor — Luke T. Shumaker</title>
  <link rel="stylesheet" href="assets/style.css">
  <link rel="alternate" type="application/atom+xml" href="./index.atom" name="web log entries"/>
</head>
<body>
<header><a href="/">Luke T. 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 &lt;stdarg.h&gt;     /* va_start()/va_end() */
#include &lt;stdio.h&gt;      /* vasprintf() */
#include &lt;stdlib.h&gt;     /* free() */
#include &lt;unistd.h&gt;     /* write() */

int
fd_printf(int fd, const char *format, ...)
{
    va_list arg;
    int len;
    char *str;

    va_start(arg, format);
    len = vasprintf(&amp;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>
  <aside class="sponsor"><p>I'd love it if you <a class="em"
      href="/sponsor/">sponsored me</a>.  It will allow me to continue
      my work on the GNU/Linux ecosystem.  Thanks!</p></aside>

<p>The content of this page is Copyright © 2013 <a href="mailto:lukeshu@lukeshu.com">Luke T. 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>