Google News
logo
C Program to Read the First Line From a File
In the following example of C Program to Read the First Line From a File :
Program :
#include <stdio.h>
#include <stdlib.h> // For exit() function
int main() {
    char c[1000];
    FILE *fptr;
    if ((fptr = fopen("program.txt", "r")) == NULL) {
        printf("Error! File cannot be opened.");
        // Program exits if the file pointer returns NULL.
        exit(1);
    }

    // reads text until newline is encountered
    fscanf(fptr, "%[^\n]", c);
    printf("Data from the file:\n%s", c);
    fclose(fptr);

    return 0;
}
If the file is found, the program saves the content of the file to a string c until '\n' newline is encountered.

Suppose the program.txt file contains the following text in the current directory.

“C” is a structured oriented programming language developed at “AT & T Bell Laboratories of USA” in 1972.

It was developed by Dennis Ritche in late 1970’s.

It began to replace the more familiar languages of that time like PL/1, ALGOL etc. ​


The output of the program will be :
Data from the file :

“C” is a structured oriented programming language developed at “AT & T Bell Laboratories of USA” in 1972.​


If the file program.txt is not found, the program prints the error message.