Jiminion
Jiminion

Reputation: 5168

Proper use of fprintf

Is this ever acceptable?

fprintf(fp,"Just a string");

or

fprintf(fp,stringvariable);

versus

fprintf(fp,"%s","Just a string");

It seems confusing to me as the string variable (or constant) is used as the formatting versus the output itself. It the string variable had format-specific content ('%s', etc.) then the output would not be as intended.

For string-only output (no formatting) which is better?

fprintf(fp,"%s",stringvariable);

or

fputs(stringvariable,fp);

Upvotes: 1

Views: 443

Answers (1)

DevSolar
DevSolar

Reputation: 70391

It is acceptable if you "know" the string variable to be "clean", if you don't care about the warning most modern compilers generate for that construct. Because:

  1. If your string contains conversion specifiers "by accident", you are invoking undefined behaviour.

  2. If you read that string from somewhere, a malicious attacker could exploit point 1. above to his ends.

It's generally better to use puts() or fputs() as they avoid this problem, and consequently don't generate a warning. (puts() also tosses in an automatic '\n'.)

The *puts() functions also have (marginally) better performance. *printf(), even on nothing more than "%s" as format string, still has to parse that conversion specifier, and count the number of characters printed for its return value.

Thanks to users 'rici' and 'Grady Player' for pointing out the character counting and compiler warning. My C got a bit rusty it seems. ;-)

Upvotes: 3

Related Questions