1

我正在尝试使用原始 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
}

有人可以帮我解决这个问题吗?十分感谢

4

2 回答 2

1

read0如果遇到文件结尾将返回:

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

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

于 2013-02-18T00:04:13.077 回答
0

intch 是未初始化的 4(或有时 8)字节。您仅将 1 个字节加载到 intch 中,而其余字节未初始化。然后将 EOF 与尚未完全初始化的所有 intch 进行比较。

尝试将 intch 声明为 char。

于 2013-02-18T00:09:00.637 回答