Maybe I'm just missing it, but isn't there a function equivalent to fprintf for file descriptors, or even a way to temporarily flip-flop between them?
You could look into dprintf
(GNU extensions, not in C or POSIX) :
The functions dprintf() and vdprintf() (as found in the glibc2 library) are exact analogues of fprintf() and vfprintf(), except that they output to a file descriptor fd instead of to a given stream.
EDIT As pointed by several of you in the comments, POSIX 2008 standardized these functions.
There is no C or POSIX (edit: prior to 2008) standard function to do printf
on a file descriptor, but you can “open” a file descriptor as a FILE *
with the POSIX-standard fdopen(int desc, const char *mode)
. I'm not sure how well supported flipping back to using the descriptor directly is, but I'm guessing it might work if you flush the buffer first…
Of course you could just implement your own using something like vsprintf
, but obviously you then have to take care of the buffering.
For what it's worth, since dprintf
is not a POSIX function, one could use the following if portability is an issue:
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <unistd.h>
int
fdprintf ( int fd, size_t bufmax, const char * fmt, ... )
{
char * buffer;
int n;
va_list ap;
buffer = ( char * ) malloc ( bufmax );
if ( !buffer )
return 0;
va_start ( ap, fmt );
n = vsnprintf ( buffer, bufmax, fmt, ap );
va_end ( ap );
write ( fd, buffer, n );
free ( buffer );
return n;
}
Most likely would want to check the return value of write
, but you get the general idea. Obviously, this does not buffer like the FILE *
routines do; I was looking more for the format specifiers and the ability to build the character data that would be written to the file descriptor, rather than worrying about buffering the data as it is being written.
No, there isn't as standard, but the two do different things. fprinft, as part of stdio, does things like buffer reads and writes, supports ungetc etc. Using a fd bypasses all that and calls the OS directly.
So they're not interchangeable. Flip flopping between them would screw up stdio buffering if nothing else
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With