Why do I get a 'ÿ' char after every include that is extracted by my parser? - C

前端 未结 3 662
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-21 13:02

I have this function:

/*This func runs *.c1 file, and replace every include file with its content
It will save those changes to *.c2 file*/
void includes_ext         


        
3条回答
  •  长情又很酷
    2020-12-21 13:15

    You major problem is this loop.

      while (!feof(header_fp)) /*copy header file content to *.c2 file*/
      {
       ch=fgetc(header_fp);
       fputc(ch,c2_fp);
      }/*while(4)*/
    

    When fgetc encounters the end of file, it will return EOF, which is a negative integer. You store this in a char and then without checking write it out to the other file.

    feof is very rarely useful as a loop condition. Most of the time it is better to check the return value of a read function.

    You should always store to return value of fgetc in an int so that you can check the return value for errors (either an end-of-file condition or some other error). fputc takes in int, in any case.

    A better way to construct the loop would be as follows.

    int ch_hdr;
    while((ch_hdr = fgetc(header_fp)) != EOF)
    {
        fputc(ch_hdr, c2_fp);
    }
    

提交回复
热议问题