In C/C++, there is a ‘write() function which let me write to either file or a socket, I just pass in the file descriptor accordingly). And there is a fprintf() which allow me to do fprintf (myFile, “hello %d”, name); but it only works for file.
Is there any api which allows me to do both?
i.e. able to let me do print formatting and able to switch between writing to file or socket?
Thank you.
You can use
sprintforsnprintfto print to achar *buffer, and then usewrite. To get a file descriptor from aFILE *variable, you can usefileno. There is no portable way to go from a file descriptor to aFILE *, though: you can portably to usefdopento associate aFILE *with a valid file descriptor.In addition, the latest POSIX standard specifies
dprintf, but the GNU libcdprintfman page has this to say:Of course, the libc manual page is not updated with the latest standard in mind, but you still have to be careful with using
dprintf, since you might get something you don’t want. 🙂