c
  1. c-program-to-read-the-first-line-from-a-file

Program to Read the First Line From a File - (C Programs)

In this tutorial, we'll discuss how to write a program in C to read the first line from a file. We'll cover the syntax, example, explanation, use, and summary of the program.

Syntax

The syntax for reading the first line from a file in C is:

#include <stdio.h>

int main() {
   FILE *fp;
   char str[100];

   fp = fopen("filename.txt", "r");
   fgets(str, 100, fp);
   printf("%s", str);

   fclose(fp);
   return 0;
}

Example

Suppose we have a file called "example.txt" with the following content:

This is the first line.
This is the second line.
This is the third line.

To read the first line from the file using a C program, we would write:

#include <stdio.h>

int main() {
   FILE *fp;
   char str[100];

   fp = fopen("example.txt", "r");
   fgets(str, 100, fp);
   printf("%s", str);

   fclose(fp);
   return 0;
}

The result of running this program would be the following output:

This is the first line.

Explanation

This program reads the first line from a file by opening the file with the fopen function. The first argument to fopen is the filename to open, and the second argument is the mode in which to open the file. In this case, we're opening the file in read mode ("r").

Once the file is open, we use the fgets function to read the first line into a buffer (str). fgets reads characters from the FILE stream until a newline character (\n) is found or the specified maximum number of characters have been read.

Finally, we print the contents of the buffer using printf and close the file with fclose.

Use

This program can be used to read and process the first line of a file in a C program. It can be integrated into more complex file processing tasks.

Summary

In this tutorial, we discussed how to write a program in C to read the first line from a file. We covered the syntax, example, explanation, use, and of the program. By using the fopen and fgets functions, we can easily read the first line of a file and process it in a C program.

Published on: