Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use fputs instead of fprintf? [closed]

Tags:

c

What exactly is the difference between the two?

like image 723
wesbos Avatar asked Apr 17 '11 02:04

wesbos


People also ask

Is Fputs thread safe?

Between a write and a subsequent read, there must be an intervening flush or reposition. Between a read and a subsequent write, there must also be an intervening flush or reposition unless an EOF has been reached. fputs_unlocked() is functionally equivalent to fputs() with the exception that it is not thread-safe.

What is the difference between fprintf and printf in C?

The fprintf function formats and writes output to stream. It converts each entry in the argument list, if any, and writes to the stream according to the corresponding format specification in format. The printf function formats and writes output to the standard output stream, stdout .

Why do we use fprintf?

The fprintf function allows you to "write" information to the screen for the user to view. This very important when user interaction is involved. The 'f' in printf stands for formatted. This means you can "format" how the data is printed in such a manner as to make it easy to read.

How does fprintf work in C?

The fprintf() function is same as printf() but instead of writing data to the console, it writes formatted data into the file. Almost all the arguments of fprintf() function is same as printf() function except it has an additional argument which is a file pointer to the file where the formatted output will be written.


2 Answers

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.

like image 69
Sadique Avatar answered Oct 13 '22 07:10

Sadique


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);   
like image 35
leonbloy Avatar answered Oct 13 '22 06:10

leonbloy