C Program to Read a Line From a File and Display

@codevarsity
 · 
2.1k views
 · 

In this sample C program, we'll learn to read text from a file and store it in a string until enter 'newline' character is encountered.

Code

#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! opening file");
        // Program exits if file pointer returns NULL.
        exit(1);         
    }

    // reads text until newline 
    fscanf(fptr,"%[^\n]", c);

    printf("Data from the file:\n%s", c);
    fclose(fptr);
    
    return 0;
}

Output

Data from the file: C programming is awesome.

Comments