我使用下面的程序从文本文件中读取并将其写入新文件,但新文件末尾总是缺少一些内容。
#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;
}
需要注意的一点是,随着我减小CHUNKSIZE,新文件末尾缺失的内容量也会减少,最后当CHUNKSIZE减小到1时会给出成功消息。如何读取和写入完整的文件而不改变CHUNKSIZE。
最佳答案
while(nread = fread(buffer, 1, CHUNKSIZE, fp)){
fwrite(buffer, 1, nread, fd);
fflush(fd);
}
写入您读取的字节!
仅当您设置大小 1 时才返回读取字节。
On success,
fread()
andfwrite()
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).
关于c - c 中的 fread 未读取完整文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27213419/