In this tutorial, we will write a program to read the first line of the file in C. Before that, you should have knowledge on the following topic in C.
To read from a text file in C, you will need to open a file stream using the fopen() function. And then check if the file exists or not. Then read the file.
C Programming Read First line of File
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #include <stdio.h> #include <stdlib.h> int main() { char c[1000]; FILE * fptr; fptr = fopen("test.txt", "r"); if (fptr == NULL) { printf("Error occured!"); exit(1); } // read the first line fscanf(fptr, "%[^\n]", c); printf("First line of the file:\n%s", c); fclose(fptr); return 0; } |
Output:
The file test.txt contains the following information.
This is simple2code.com.
This is a programming website to learn programming languages.
After successful execution of the above program, the following output will be displayed.
First line of the file:
This is simple2code.com.