c - c 中的 fread 未读取完整文件

标签 c buffer fread

我使用下面的程序从文本文件中读取并将其写入新文件,但新文件末尾总是缺少一些内容。

#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() 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).

关于c - c 中的 fread 未读取完整文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27213419/

相关文章:

c - C 和 dlc 编译器出现奇怪的解析错误

c - 尝试学习 malloc 的问题

c - 如何检查字符串是否在二进制文件中

c++ - 转到文件中的特定行并阅读它

mysql - 缓冲池使用百分比查询返回无效结果

C fread fwrite 位于文件开头

c - 如何在C++Builder项目的Delphi单元中使用Crtl? (或链接到 C++Builder C 运行时库)

c - 如何复制 "casted"字符串中的字符?

c - ffmpeg c api 中的 av_register_all() 与 avcodec_register_all() 有什么区别?

javascript - 在没有 FileReader 的 NodeJS 中 Blob 到 Base64