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

前端 未结 3 658
爱一瞬间的悲伤
爱一瞬间的悲伤 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: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);
    }
    

提交回复
热议问题