To write a C program that reads the first line from a file, you can use the fgets
function to read the content of the file line by line. Here's a C program that reads the first line from a file:
#include <stdio.h>
int main() {
// Declare a FILE pointer
FILE *file;
// Open the file for reading
file = fopen("input.txt", "r");
// Check if the file was opened successfully
if (file == NULL) {
printf("Failed to open the file for reading.\n");
return 1; // Exit the program with an error code
}
// Read the first line from the file using fgets
char line[256]; // Assuming a maximum line length of 255 characters
if (fgets(line, sizeof(line), file) != NULL) {
// Print the first line
printf("The first line from the file is:\n%s", line);
} else {
printf("The file is empty.\n");
}
// Close the file
fclose(file);
return 0; // Exit the program with a success code
}
Explanation:
The program opens a file called "input.txt" in read mode using the
fopen
function.It checks if the file was opened successfully. If the file doesn't exist or there is an issue with opening it, the program displays an error message and exits with an error code.
It declares a character array
line
to store the line read from the file. In this example, it is assumed that each line will be at most 255 characters long. You can adjust the buffer size as needed.The
fgets
function is used to read the first line from the file. It takes three arguments: the buffer where the line is stored, the size of the buffer, and the file pointer. Iffgets
successfully reads a line, it stores it in theline
buffer.The program checks if
fgets
successfully read a line. If so, it prints the first line to the console. If the file is empty, it displays a message indicating that the file is empty.The program closes the file using
fclose
to release system resources.
Output (for example, if "input.txt" contains the following lines):
The first line from the file is:
This is the first line.
This program opens the file "input.txt," reads the first line from it,
and prints it to the console. If the file is empty, it will display a
message indicating that the file is empty.