![]() |
VOOZH | about |
In C, reading input until the End of the File (EOF) involves reading input until it reaches the end i.e. end of file. In this article, we will learn various methods through which we can read inputs until EOF in C.
Reading Input Until EOF
The method is a built in method provided in C which reads one character at a time from the standard input. The getchar() function returns the character read as unsigned char cast to an integer or EOF on reaching end of the file.
int getchar(void)
getchar() function does not take any parameters and returns EOF if the end of the file is reached or user terminated the execution.
The following program illustrates how we can read input until EOF in C using getchar() function.
Output
Enter text
Press (Ctrl+D on Unix or Ctrl+Z on Windows to terminate the loop):
G
You entered: G
E
You entered: E
E
You entered: E
K
You entered: K
S
You entered: S
EOF reached. Program terminated.
Time Complexity:O(N), where N is the number of inputs.
Auxiliary Space: O(1)
The fgets() function in C is used to read a line of a text at a time using a fixed size buffer. The fgets() function reads up to buffersize-1 characters from the standard input and stores them in the buffer. It stops it's execution whenever it encounters a newline character or EOF, thus it can be used to read input until EOF in C.
char *fgets(char *str, int n, FILE *buffer);
Here,
The following program illustrates how we can read input until EOF in C using fgets() function.
Output
Enter text (Press Ctrl+D on Unix or Ctrl+Z on Windows for EOF):
Hello Geeks
You entered: Line 1: Hello Geeks
This is a tutorial for
You entered: Line 2: This is a tutorial for
Reading inputs in C
You entered: Line 3: Reading inputs in C
Until EOF is encountered
You entered: Line 4: Until EOF is encountered
EOF reached. Total lines read: 4
Time Complexity: O(N), where N is the number of inputs.
Auxiliary Space: O(M), where M is the size of the buffer.
The method can also be used to read inputs until EOF in C. Scanf automatically terminates the execution of the program whenever it encounters an EOF. Followis is the syntax to use scanf() function:
int scanf(const char *format, ...);
Here,
The following program illustrates how we can read input until EOF in C using scanf() function.
Output
Enter your inputs or (PressCtrl+D on Unix or Ctrl+Z on Windows for EOF):
10
You entered: Number 1: 10
20
You entered: Number 2: 20
30
You entered: Number 3: 30
40
You entered: Number 4: 40
50
You entered: Number 5: 50
EOF reached. Total numbers read: 5
Time Complexity:O(N), where N is the number of inputs.
Auxiliary Space: O(1)