1

The C standard provides two functions, puts and fputs, with puts(s) behaving as fputs(s, stdout) except that it additionally appends a newline:

The puts() function shall write the string pointed to by s, followed by a <newline>, to the standard output stream stdout.

What is the rationale for this difference in behavior between puts and fputs?

vitaut
  • 49,672
  • 25
  • 199
  • 336
  • Maybe because stdout is line buffered by default and will print when it reaches a newline. More convenient then flushing or adding new line manually. – Tony Tannous May 17 '20 at 14:07
  • 2
    It's mostly a question of ”that is the way it was designed in the late 70s”. There was an analogous discrepancy between `gets()` and `fgets()`. However, `gets()` is no longer part of standard C, for solid security reasons, so with luck you aren't aware of it, and it is best to stay that way. – Jonathan Leffler May 17 '20 at 14:19

1 Answers1

2

The puts function specifically writes to stdout which is commonly a console. Because console output is typically line bufered, it's convenient to not have to explicitly add a newline to a string to print.

The fputs function can write to any given FILE object, not just stdout, so by not automatically adding a newline it makes the function more flexible in the general case.

dbush
  • 205,898
  • 23
  • 218
  • 273