简体   繁体   中英

fread in c not reading the complete file

I used the program below to read from a text file and write the same to a new file, but the new file always has some missing content at the end.

#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>

#define CHUNKSIZE 256


int main(){

  const char *file_name = "file.txt";
  const char *new_file_name = "new_file.txt";
  struct stat b_st;
  struct stat n_b_st;
  int file_size, new_file_size;
  char buffer[CHUNKSIZE];
  FILE *fp = fopen(file_name, "rb");
  FILE *fd = fopen(new_file_name, "wb");


  while(fread(buffer, sizeof(buffer), 1, fp)){

    fwrite(buffer, sizeof(buffer), 1, fd);
    fflush(fd);
  }

  stat(file_name, (struct stat *)&b_st);
  stat(new_file_name, (struct stat *)&n_b_st);

  file_size = b_st.st_size;
  new_file_size = n_b_st.st_size;

  if(file_size == new_file_size){

    printf("Success reading and writing data");
    exit(1);
  }

  return 0;  

}    

One point to notice is, as much i reduce the CHUNKSIZE, the amount of content missing at the end in new file is reduced and finally it gives success message when CHUNKSIZE is reduced to 1. How is it possible to read and write the complete file without changing CHUNKSIZE.

while(nread = fread(buffer, 1, CHUNKSIZE, fp)){
    fwrite(buffer, 1, nread, fd);
    fflush(fd);
}

Write bytes which you read!

Read bytes are only returned when you set size 1.

On success, fread() and fwrite() return the number of items read or written. This number equals the number of bytes transferred only when size is 1. If an error occurs, or the end of the file is reached, the return value is a short item count (or zero).

the problem you have it is because your unit size is too big, try this:

int ret;
while((ret = fread(buffer,1, sizeof(buffer), fp)) > 0){
fwrite(buffer, 1, ret, fd);

fflush(fd);}

read man pages for more information

you should also check return values for all of your program (for fopen and fread/fwrite).

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