Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

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:
", 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 ?

question from:https://stackoverflow.com/questions/65599881/c-fwrite-vs-fprintf

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...