簡體   English   中英

如何停止從C中的二進制文件讀取

[英]how to stop reading from binary file in 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
}

有人可以幫助我解決這個問題嗎? 非常感謝

如果遇到文件結尾,則read將返回0

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

請注意,負值表示錯誤,因此您可能要保存read的返回值。

intch未初始化的4(或8)字節。 您僅將1個字節加載到intch中,而其余字節未初始化。 然后,您將EOF與尚未完全初始化的所有intch進行比較。

嘗試將intch聲明為char。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM