Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is EOF in the C programming language?

Tags:

c

input

eof

How do you get to see the last print? In other words what to put in for EOF? I checked the definitions and it says EOF is -1.

And if you enter Ctrl-D you won't see anything.

#include <stdio.h>  int main() {  int c;  while((c = getchar() != EOF)) {   printf("%d\n", c);  }  printf("%d - at EOF\n", c); } 
like image 206
Chris_45 Avatar asked Nov 23 '09 09:11

Chris_45


People also ask

What is EOF and its value in C?

EOF instead is a negative integer constant that indicates the end of a stream; often it's -1, but the standard doesn't say anything about its actual value. C & C++ differ in the type of NULL and '\0' : in C++ '\0' is a char , while in C it's an int ; this because in C all character literals are considered int s.

Why is EOF used?

Use EOF to avoid the error generated by attempting to get input past the end of a file. The EOF function returns False until the end of the file has been reached. With files opened for Random or Binary access, EOF returns False until the last executed Get statement is unable to read an entire record.


2 Answers

On Linux systems and OS X, the character to input to cause an EOF is Ctrl-D. For Windows, it's Ctrl-Z.

Depending on the operating system, this character will only work if it's the first character on a line, i.e. the first character after an Enter. Since console input is often line-oriented, the system may also not recognize the EOF character until after you've followed it up with an Enter.

And yes, if that character is recognized as an EOF, then your program will never see the actual character. Instead, a C program will get a -1 from getchar().

like image 187
Carl Smotricz Avatar answered Nov 04 '22 17:11

Carl Smotricz


You should change your parenthesis to

while((c = getchar()) != EOF) 

Because the "=" operator has a lower precedence than the "!=" operator. Then you will get the expected results. Your expression is equal to

while (c = (getchar()!= EOF)) 

You are getting the two 1's as output, because you are making the comparison "c!=EOF". This will always become one for the character you entered and then the "\n" that follows by hitting return. Except for the last comparison where c really is EOF it will give you a 0.

EDIT about EOF: EOF is typically -1, but this is not guaranteed by the standard. The standard only defines about EOF in section 7.19.1:

EOF which expands to an integer constant expression, with type int and a negative value, that is returned by several functions to indicate end-of-file, that is, no more input from a stream;

It is reasonable to assume that EOF equals -1, but when using EOF you should not test against the specific value, but rather use the macro.

like image 38
Lucas Avatar answered Nov 04 '22 19:11

Lucas