First User
First User

Reputation: 761

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 ?

Upvotes: 1

Views: 2890

Answers (2)

chux
chux

Reputation: 153338

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.

Upvotes: 2

but was there any specific reason the author chose to use fwrite() over fprintf or printf in this context ?

Study the implementation of fwrite and fprintf inside GNU libc.

You'll find out that fprintf is more complex and more brittle, so slower, than fwrite is. It is also a lot harder to understand.

AFAIK, some compilers (including sometimes GCC) are able to optimize (in simple cases) some call to fprintf into something similar to your fwrite. You might try compiling your foo.c source code as gcc -Wall -O3 -fverbose-asm -S foo.c and look into the generated assembler code foo.s

Upvotes: 1

Related Questions