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

前端 未结 3 654
爱一瞬间的悲伤
爱一瞬间的悲伤 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);
    }
    
    0 讨论(0)
  • 2020-12-21 13:18

    If you look at your code you have to places where you write to the target file.

    If I were you I would set a break point at

            }/*frst if*/
            else
            {
            fputc(ch,c2_fp); // brk point here
            }
    

    to check what you are actually writing there.

    0 讨论(0)
  • 2020-12-21 13:21

    "ÿ" corresponds to the code point 0xFF. fgetc returns EOF when the end of file is reached, which is (usually) defined as -1. Store -1 in a char and you'll wind up with 0xFF. You must check for EOF between calling fgetc and fpuc.

    int ch;
    ...
    /*copy header file content to *.c2 file*/
    for (ch=fgetc(header_fp); ch > -1; ch=fgetc(header_fp)) {
       fputc(ch,c2_fp);
    }
    

    Instead of getting characters one at a time, you could use fgets to get a block of characters.

    #ifndef BUFSIZE
    #  define BUFSIZE 1024
    #endif
    char buf[BUFSIZE], *read;
    ...
    /*copy header file content to *.c2 file*/
    while ((read = fgets(buf, BUFSIZE, header_fp))) {
        fputs(buf, c2_fp);
    }
    
    0 讨论(0)
提交回复
热议问题