簡體   English   中英

為什么 fgetc 返回 ffffffff 而不是文件中的實際數據?

[英]Why is fgetc returning ffffffff instead of actual data in file?

我正在編寫一個程序來讀取一個十六進制圖像文件,並將其中的一部分寫入另一個文件。

當我閱讀它時,文件的某些部分被正確讀取,但介於兩者之間的某個地方開始讀取並返回FF而不是文件中的實際十六進制數據。

我已將unsigned char ch用於ch=fgetc(sourceImageFile)

我不明白我哪里出錯了,為什么它會在兩者之間返回長長的FF行。 請幫我。 我還保留了一個輸入文件 as.txt 以便能夠打開它並進行調試。

這是我的代碼:

#include<stdio.h>
#include<string.h>

int main()
{
  FILE* source;
  FILE* sr, * sg, * sb;
  int i = 1;

  source = fopen("file.L-4", "r");
  sr = fopen("red.img", "wb+");
  sg = fopen("green.img", "wb+");
  sb = fopen("blue.txt", "wb+");

  fseek(source, 540, SEEK_SET);
  printf("\nDone phew!\n");
  unsigned char ch;
  int l = 1;
  unsigned char buf[10];
  while (l <= 5279)
  {

    fseek(source, 32, SEEK_CUR);
    i = 1;
    while (i <= 4919 && l < 5280)
    {
      ch = fgetc(source);

      sprintf(buf, "%02x ", ch);
      fputs(buf, sb);
      i++;
    } //BLUE done
    l++;
    //fseek(source,9902,SEEK_CUR);


    fseek(source, 32, SEEK_CUR);
    i = 1;
    while (i <= 4919 && l < 5280)
    {
      ch = fgetc(source);

      sprintf(buf, "%02x ", ch);
      fputs(buf, sg);
      i++;
    } //GREEEN done
    l++;

    fseek(source, 32, SEEK_CUR);
    i = 1;
    while (i <= 4919 && l < 5280)
    {
      ch = fgetc(source);

      sprintf(buf, "%02x ", ch);
      fputs(buf, sr);
      i++;
    } //RED done
    l++;


    //printf("%d  ",l);
  }
  printf("\nthis is done too!\n");
  fclose(sr);
  fclose(sg);
  fclose(sb);
  fclose(source);
  return 0;
}

只是解釋@kaylum 已經告訴你的內容。 當您將結果存儲在unsigned char中時, fgetc()返回一個int 這意味着您無法從ch中分辨出您讀取的是0xff還是 EOF (EOF 在我的系統上定義為 -1,而在 2 的補碼中定義為0xff )。 在處理二進制數據時,您要更改類型。 始終檢查返回值!

int ch;
...
if((ch = fgetc(source)) == EOF) {
   // nothing more to read
}

暫無
暫無

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

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