summaryrefslogtreecommitdiff
path: root/public/fd_printf.md
blob: 51e16aa78b05ebcfec9c60f199e7697d3abd78cf (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
`dprintf`: print formatted text directly to a file descriptor
===============================================================
---
date: "2013-10-12"
license: WTFPL-2
---

This already existed as `dprintf(3)`.  I now feel stupid for having
Implemented `fd_printf`.

The original post is as follows:

----

I wrote this while debugging some code, and thought it might be useful
to others:

	#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;
	}

It is a version of `printf` that prints to a file descriptor—where
`fprintf` prints to a `FILE*` data structure.

The appeal of this is that `FILE*` I/O is buffered—which means mixing
it with raw file descriptor I/O is going to produce weird results.