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.
freadis not supposed to write into a file. I would consider changing the title.