C Program to Read the First Line From a File

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

#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.