|
-
September 20th, 2004, 02:56 PM
#1
Junior Member
(X)printf()
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?
-
September 20th, 2004, 03:00 PM
#2
From man fprintf:
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).
Oliver's Law:
Experience is something you don't get until just after you need it.
-
September 20th, 2004, 03:05 PM
#3
Junior Member
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.
-
September 20th, 2004, 03:14 PM
#4
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.
-
September 20th, 2004, 03:19 PM
#5
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.
Oliver's Law:
Experience is something you don't get until just after you need it.
-
September 20th, 2004, 09:46 PM
#6
Junior Member
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.
-
September 21st, 2004, 09:25 AM
#7
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);
Oliver's Law:
Experience is something you don't get until just after you need it.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
|