Search code examples
cprintffputs

What is the difference between printf("%s"), printf(s) and fputs?


char s[100]={0};
fgets(s, sizeof(s), stdin);

In the context of the code above, what is the difference between these three?

  1. printf("%s",s);
  2. printf(s);
  3. fputs(s,stdout);

Solution

    1. printf("%s",s); correct but printf is a very heavy function and most compilers will actually replace it with puts in the compiler code if the format string ends with '\n'

    2. printf(s); very dangerous as the format string may contain % and then it will expect another parameters. If it happens it is UB. It also makes your code exploit prone

    3. fputs(s,stdout); OK. Not as heavy as printf but will add the new line