How to Read Input Until EOF in C?
Last Updated :
03 Jul, 2024
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.
The getchar() 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.
Syntax
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.
C
// C program to read input until EOF using getchar()
#include <stdio.h>
int main()
{
// Variable to store each character read
int ch;
printf("Enter text\nPress (Ctrl+Z to terminate the "
"loop):\n");
// Read characters until EOF is encountered
while ((ch = getchar()) != EOF) {
// Print each character as it's read
if (ch != '\n') {
printf("You entered: %c\n",
ch); // Print the character entered
}
}
printf("\nEOF reached. Program terminated.\n");
return 0;
}
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.
Syntax
char *fgets(char *str, int n, FILE *buffer);
Here,
- str: Pointer to an array of chars where the string is stored.
- n: Denotes the maximum number of characters to be read (including the null character).
- buffer: Pointer to a FILE object that identifies the stream to read from.
- Return value: Returns the read str on success and on failure returns EOF.
The following program illustrates how we can read input until EOF in C using fgets() function.
C
// C program to read input until EOF using fgets()
#include <stdio.h>
#include <string.h>
#define MAX_LENGTH 1000 // Maximum length of input line
int main()
{
// Buffer to store each line
char line[MAX_LENGTH];
// Counter for number of lines read
int line_count = 0;
printf("Enter text (Press Ctrl+D on Unix or Ctrl+Z on "
"Windows for EOF):\n");
// Read lines until EOF is encountered
while (fgets(line, MAX_LENGTH, stdin) != NULL) {
line_count++;
// Remove the newline character at the end of the
// line, if it exists
line[strcspn(line, "\n")] = 0;
// Print each line with its line number
printf("You entered: Line %d: %s\n", line_count,
line);
}
printf("\nEOF reached. Total lines read: %d\n",
line_count);
return 0;
}
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 scanf() 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:
Syntax
int scanf(const char *format, ...);
Here,
- format: It is a C string that contains the format specifers.
- return value: Number of input items successfully matched and assigned. Returns EOF if an error occurs or end of input is reached before any data is successfully read.
The following program illustrates how we can read input until EOF in C using scanf() function.
C
// C program to read input until EOF using scanf()
#include <stdio.h>
#include <string.h>
// Maximum length of input line
#define MAX_LENGTH 1000
#include <stdio.h>
int main()
{
// Variable to store each number read
int num;
// Counter for number of integers read
int count = 0;
printf("Enter your inputs or (PressCtrl+D on Unix or "
"Ctrl+Z on Windows for EOF):\n");
// Read integers until EOF is encountered
while (scanf("%d", &num) != EOF) {
count++;
// Print each number with its count
printf("You entered: Number %d: %d\n", count, num);
}
printf("\nEOF reached. Total numbers read: %d\n",
count);
return 0;
}
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)
Similar Reads
C Programming Language Tutorial
C is a general-purpose mid-level programming language developed by Dennis M. Ritchie at Bell Laboratories in 1972. It was initially used for the development of UNIX operating system, but it later became popular for a wide range of applications. Today, C remains one of the top three most widely used
5 min read
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response
In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Backpropagation in Neural Network
Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Polymorphism in Java
Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
In C, a variable defined in a function is stored in the stack memory. The requirement of this memory is that it needs to know the size of the data to memory at compile time (before the program runs). Also, once defined, we can neither change the size nor completely delete the memory.To resolve this,
9 min read
3-Phase Inverter
An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
What is Vacuum Circuit Breaker?
A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read