我使用下面的程序从文本文件读取并将其写入新文件,但是新文件最后总是缺少一些内容。
#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时返回。
如果成功,
fread()
并fwrite()
返回读取或写入的项目数。此数字等于仅在size为1时传输的字节数。如果发生错误或到达文件末尾,则返回值为短项计数(或零)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句