Comparing unsigned char and EOF

前端 未结 6 2139
小蘑菇
小蘑菇 2020-11-29 08:59

when the following code is compiled it goes into an infinite loop:

int main()
{
    unsigned char  ch;
    FILE *fp;
    fp = fopen(\"abc\",\"r\");
    if(fp         


        
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-29 09:19

    I have encountered this problem too. My solution is to use feof().

    unsigned int xxFunc(){
      FILE *fin;
      unsigned char c;
      fin = fopen("...", "rb");
      if(feof(fin) != 0) return EOF;
      c = fgetc(fin);
      fclose(fin);
    ...
    }
    

    And you can define an int variable to compare with EOF. For example:

    int flag = xxFunc();
    while(flag != EOF) {...}
    

    This works for me.

    **IMPORTANT UPDATE***

    After using the method I mentioned before, I found a serious problem. feof() is not a good way to break the while loop. Here is the reason for it. http://www.gidnetwork.com/b-58.html

    So I find a better way to do this. I use an int variable to do it. here:

    int flag;
    unsigned char c;
    while((flag = fgetc(fin)) != EOF) 
    { 
      //so, you are using flag to receive, but transfer the value to c later.
      c = flag;
      ... 
    }
    

    After my test, this works.

提交回复
热议问题