When should I use fputs instead of fprintf?
Asked Answered
R

3

45

What exactly is the difference between the two?

Rector answered 17/4, 2011 at 2:4 Comment(3)
Not to be a jerk, but did you check the documentation for the two functions? One does formatted output, the other outputs a string, unformatted, to the stream. Do you have a specific question?Tantalate
What does your handy C reference manual say?Fireguard
fputs(s, f) is functionally equivalent to fprintf(f, "%s", s). They both compile to the same code (a call to fputs) with modern optimizing compilers.Birkett
W
47

fprintf does formatted output. That is, it reads and interprets a format string that you supply and writes to the output stream the results.

fputs simply writes the string you supply it to the indicated output stream.

fputs() doesn't have to parse the input string to figure out that all you want to do is print a string.fprintf() allows you to format at the time of outputting.

Wigwam answered 17/4, 2011 at 2:7 Comment(1)
I may be wrong but fputs is safer if you wanted to print a string controlled by user. There are a lot of posts on StackOverflow talking about that.Shastashastra
F
15

As have been pointed out by other commenters (and as it's obvious from the docs) the great difference is that printf allows formatting of arguments.

Perhaps you are asking if the functions are equivalent where no additional arguments are passed to printf()? Well, they are not.

   char * str;
   FILE * stream;
   ...
   fputs(str,stream);    // this is NOT the same as the following line
   fprintf(stream,str);  // this is probably wrong

The second is probably wrong, because the string argument to fprintf() is a still a formating string: if it has a '%' character it will be interpreted as a formatting specifier.

The functionally equivalent (but less direct/efficient/nice) form would be

   fprintf(stream,"%s", str);  
Fro answered 17/4, 2011 at 2:49 Comment(0)
Y
5

Uhm... ...puts() just writes a string, while printf() has a number of formatting facilities for several types of data.

fputs() http://www.cplusplus.com/reference/clibrary/cstdio/fputs/

fprintf() http://www.cplusplus.com/reference/clibrary/cstdio/fprintf/

Documentation is useful! Learn to read it, and you'll have a powerful tool on your side.

Yellowtail answered 17/4, 2011 at 2:8 Comment(1)
puts / printf is not an exact correlation to fputs / fprintf. puts appends a '\n' to its output, unlike any of the other functions.Oniskey

© 2022 - 2024 — McMap. All rights reserved.