EOF in C, what is EOF?

107 Views Asked by At

I have some questions about EOF in C.

  1. What is actually EOF? I have read that it is a macro that "expands" to -1. What does this mean? Specifcally what does "expand" mean in this case?

I have this code:

#include <stdio.h>

int main()
{
    int c;
    scanf("%d", &c);
    if (c==EOF){printf("c is EOF");}
    else {printf("C is not EOF");}
}

Output:

1
C is not EOF
    
-1
c is EOF
    
^Z
  1. In the code, if I write -1, I get that this is EOF. But from what I have read, EOF is not really -1, because we can write -1 at the end of a file?

  2. I have read that on windows to get EOF you need to type CTRL+Z. But when I try to type this and press enter in the terminal, nothing happens, as I demonstrate in the last example in the code. What am I doing wrong?

2

There are 2 best solutions below

2
gulpr On BEST ANSWER

What is actually EOF? I have read that it is a macro that "expands" to -1. What does this mean? Specifically what does "expand" mean in this case?

It means that it is defined as C macro for example:

#define EOF -1

What is EOF?

EOF indicates that the last operation on the file or stream has reached its end.

The C preprocessor textually replaces occurrences of the EOF in your source code with -1

Your code is wrong. scanf returns EOF not scans it. It should be:

int main()
{
    int c, val;
    c = scanf("%d", &val);
    if (c==EOF){printf("c is EOF");}
    else {printf("C is not EOF");}
}

But scanf will almost never return EOF unless you provide a special key combination to force it.

2
glglgl On

You are confusing several concepts and layers.

Let's start at the top:

What is EOF?

EOF means End of file. That's when you hit the end of a file on the file system.

How is EOF signalled?

That depends on the function you use.

When using read(), it means you have a "short read": if you try to read 1024 bytes, but only get 400, you are likely at the end of the file. But you can only be sure if ou read again and you get 0 bytes.

Under Linux, pressing Ctrl-D when reading from the console just stops the current read() call which might result in a "short read()". Pressing it a second time leads to read() returning 0.

There are other ways of reading, that are getc() and scanf().

getc() returns an int: either the code of the character which was read, or if there is nothing to read, it returns -1 which is the value of EOF.

scanf(), however, just returns fewer elements or none at all. In the latter case, it retuens -1 / EOF in order to signal that feof() and/or ferror() should be checked. Details can be read in any decent description of that function.