0

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?

chqrlie
  • 131,814
  • 10
  • 121
  • 189
Brandon
  • 401
  • 5
  • 20

1 Answers1

0

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.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
  • I want the line to be put back into the input stream. So would I have to add ungetc into both the if-statment and the else? – Brandon Jan 20 '16 at 03:08
  • You cannot put back a whole line into the input stream with `ungetc`, at most one byte can be put back. No need to put anything back in the `else` part since you did not read a byte, you hit the end-of-file. – chqrlie Jan 20 '16 at 03:10
  • My intention for calling fgetc is to find out if it is EOF or not. If not I want it to continue reading as normal which is why I want the char to be put back into the stream. So would I need to put ungetc in if and the else part? – Brandon Jan 20 '16 at 03:12
  • Also would it be a problem if I declare c as an char instead of an int? I ask because if i want to feed it back into the ungetc it would have to be char right? – Brandon Jan 20 '16 at 03:19
  • `c` must be declared `int` because `fgetc()` can return all byte values **plus** `EOF`, that's too many possibilities for a `char`. I modified the answer for your purpose. – chqrlie Jan 20 '16 at 03:27
  • I already gave you a detailed answer here: http://stackoverflow.com/questions/34888776/does-feof-work-when-called-after-reading-in-last-line . What do you not understand? Checking for end of file this way is not idiomatic in C, what is the context that makes you think it is pertinent? – chqrlie Jan 20 '16 at 03:33