如何在c中停止从二进制文件中读取

时间:2013-02-17 23:59:09

标签: c

我正在尝试使用原始I / O函数从文件中读取数据并将数据输出到另一个文件 但是,似乎我的代码无法工作,我发现这是read()无法终止。但是,我不知道如何终止循环,我的代码是这样的:

int main(){
   int infile; //input file
   int outfile; //output file

   infile = open("1.txt", O_RDONLY, S_IRUSR);
   if(infile == -1){
      return 1; //error
   }
   outfile = open("2.txt", O_CREAT | ORDWR, S_IRUSR | S_IWUSR);
   if(outfile == -1){
      return 1; //error
   }

   int intch; //character raed from input file
   unsigned char ch; //char to a byte

   while(intch != EOF){ //it seems that the loop cannot terminate, my opinion
      read(infile, &intch, sizeof(unsigned char));
      ch = (unsigned char) intch; //Convert
      write(outfile, &ch, sizeof(unsigned char));
  }
   close(infile);
   close(outfile);

   return 0; //success
}

有人可以帮我解决这个问题吗?你好多了

2 个答案:

答案 0 :(得分:1)

如果遇到文件结尾,

read将返回0

while(read(infile, &intch, sizeof(unsigned char) > 0){ 
    ch = (unsigned char) intch; //Convert
    write(outfile, &ch, sizeof(unsigned char));
}

请注意,负值表示错误,因此您可能希望保存read的返回值。

答案 1 :(得分:0)

intch是未初始化的4(或有时8个)字节。您只是将1个字节加载到intch中,并将剩余的字节保留为未初始化。然后,将EOF与所有未完全初始化的intch进行比较。

尝试将intch声明为char。