Search code examples
cprintffwrite

C: fwrite() vs (f)printf?


I was reading the manual page for the getline function and saw a demonstration of it :

 #define _GNU_SOURCE
       #include <stdio.h>
       #include <stdlib.h>

       int
       main(int argc, char *argv[])
       {
           FILE *stream;
           char *line = NULL;
           size_t len = 0;
           ssize_t nread;

        ...
           while ((nread = getline(&line, &len, stream)) != -1) {
               printf("Retrieved line of length %zu:\n", nread);
               fwrite(line, nread, 1, stdout); /* ? */
           }

           free(line);
           fclose(stream);
           exit(EXIT_SUCCESS);
       }

I replaced the fwrite() statement with printf ("%s", line) and it produced identical results (compared using cmp and diff). I am aware of the distinction between fwrite and fprint but was there any specifc reason the author chose to use fwrite() over fprintf or printf in this context ?


Solution

  • Difference between fwrite(line, nread, 1, stdout) and printf ("%s", line) includes:

    printf ("%s", line) writes up to the 1st null character.

    fwrite(line, nread, 1, stdout) writes to length of input.

    This differs when a null character was read and so using fwrite() provides correct functionality in that pathological case.