简体   繁体   中英

Using fread and fwrite

I am trying to learn how to use fread and fwrite. Here I am trying to print the contents of a file on standard output.

#include <stdio.h>

int main()

{
FILE *fp; 
fp = fopen("largest.c", "r+");
int c = fwrite(fp, sizeof(fp), 1, stdout);

printf("Output is 1 if write succesful! : %d\n", c);

return 0;
}

This doesn't work. Shows some garble on the screen. why?

Because you are never reading from the file you opened.

Instead, you are dumping the in-memory definition of the FILE data structure (something which is internal to the standard library implementation) to stdout , producing garbled output.

You must have a buffer of bytes, into which you first read from fp , then write the newly-read data to stdout :

FILE *fp;
char buffer[4096];

/* ... */
const size_t got = fread(buffer, 1, sizeof buffer, fp);
fwrite(buffer, 1, got, stdout);

The above adds a buffer of characters, and does a single fread() call to attempt to fill that buffer with data from the fp file (I didn't repeat the fopen() call, that should still happen of course).

It then calls fwrite() , handing it the buffer containing data read from the file.

Note that this will read (and thus write) at most up to 4096 characters; if the input file is larger you won't see the remaining data. This can be fixed by doing the above in a loop, stopping when fread() returns 0.

By the way, your usage reminds me of the Linux-specific sendfile() function, where you really do get to skip doing the reading at the application level. Instead that's done inside the kernel, which presumably opens it up for optimizations. This is probably a bit above your current level, though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM