Search code examples
cfgetc

Will fgetc(fileName) pull a character if it is within an IF statment?


This is the if statement I have:

if (fgetc(fileName) != EOF) {
}

I know if I run fgetc() when not within the if statement it will remove a character and I would have to do ungetc to return it. Will this happen when the fgetc is within the if statement?


Solution

  • Yes it will, and since you did not store the byte that was read, you lost it. Use this instead:

    int c;
    if ((c = fgetc(fp)) != EOF) {
        ungetc(c, fp);   /* put the byte back into the input stream */
        /* not at end of file, keep reading */
        ...
    } else {
        /* at end of file: no byte was read, nothing to put back */
    }
    

    Also note that you should pass a FILE* to fgetc, not a filename, and ungetc does not return the character, but puts it back into the input stream so it can be read by the next fgetc() or fgets()... You may not be able to ungetc more than one byte at a time before reading again from the stream.