简体   繁体   English

在C中读取未读取完整文件

[英]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. 需要注意的一点是,我减少了CHUNKSIZE的程度,减少了新文件末尾丢失的内容数量,最后,当CHUNKSIZE减小为1时,它给出了成功消息。如何读取和写入完整的文件而不更改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. 读字节仅在设置大小1时返回。

On success, fread() and fwrite() return the number of items read or written. 成功时, fread()fwrite()返回读取或写入的项目数。 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). 该数字等于仅在size为1时传输的字节数。如果发生错误或到达文件末尾,则返回值为短项计数(或零)。

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). 您还应该检查所有程序的返回值(对于fopen和fread / fwrite)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM