In this tutorial, you will learn how to write a C program to read the first line from a file.
Program to Read the First Line From a File
In this program, the header file <stdlib.h>
is used because we are using the exit()
function that belongs to this file.
If the file is found then the fscanf()
function reads the content of the file until '\n'
(new line) is encountered in the file.
If the file doesn’t exist then the pointer returned by fopen()
function returns NULL, if the ptr is null then we are displaying the error message to the user and exiting the program using exit(1).
#include <stdio.h>
#include <stdlib.h>
int main() {
char ch[1000];
FILE *fptr;
if ((fptr = fopen("beginnersbook.txt", "r")) == NULL) {
printf("Error! File does not exist.");
// beginnersbook.txt exits if the file pointer returns NULL.
exit(1);
}
// reading text using fscanf() till a new line is
// encountered and printed the same line using printf()
fscanf(fptr, "%[^\n]", ch);
printf("Data from the file:\n%s", ch);
fclose(fptr);
return 0;
}
Output: This is the output of the program, it printed the first file of the file. Refer the next screenshot to see the full content of the file.
File content: This is the file content, it contains two sentences. However we are reading the first line from the file, so only the first line gets printed as the output of the above program.