Which printf's should I use in which circumstances? Like when would be using fprintf(), snprintf(), or any of the non-printf()'s be appropriate and usefull?
Printable View
Which printf's should I use in which circumstances? Like when would be using fprintf(), snprintf(), or any of the non-printf()'s be appropriate and usefull?
From man fprintf:
Quote:
The printf() family of functions produces output according to a format as
described below. Printf() and vprintf() write output to stdout, the
standard output stream; fprintf() and vfprintf() write output to the
given output stream; sprintf(), snprintf(), vsprintf(), and vsnprintf()
write to the character string str; and asprintf() and vasprintf() dynami-
cally allocate a new string with malloc(3).
So, my interpretation of this:
printf() simply writes to stdout - you don't/can't specify a stream
fprintf() would really only be needed for writing to stderr?
I'm still not sure when snprintf() would need to be used - nor do I really understand what all the v(x)printf's are.
i suppose printf() is used for writin to stdout and printing statements on screen and fprintf for files n streams,etc;when using the concept of file handling. fprintf() is not only needed for writing to stderr but also stdout(i suppose). and snprintf() is used to print statements or write it on stdout using a particular mentioned string.
Close enough ;-)
You can also use fprintf to write to any stream, not just STDERR. One you opened with open() ie.
You can use sprintf() to format a string without printing it. Say you need a string with a number in a certain format.
int nb_int=32;
char nb[20];
sprintf( &nb, "%00X", nb_int);
After this nb will contain the string "20". Simple decimal->hex converter ;-)
Never used any of the v* commands, so I've got no idea when to use 'm.
Thanks for the replies. I've done a little bit of researching myself after SirDice's comment. Apparently, one should never use sprintf(). Nasty buffer overrun waiting to happen - snprintf() would be the secure way of doing it. Appreciate the help guys.
On a side note since you mentioned security ;)
Watch out with printf() too!
Something like this may bite you: printf(str);
If str is user-supplied you've opened up a format-string hole.
If you need to print user supplied strings do a printf("%s",str);