C Program to Read a Line From a File and Display it
This program reads text from a file and stores it in a string until entering the ‘newline’ character is encountered.
Example: Program to read text from a file
#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;
}
If the file program.txt
is not found, this program prints an error message.
If the file is found, the program saves the file’s content to a string c until the ‘\n’ newline is encountered.
Suppose, the program.txt
file contains the following text.
C programming is awesome. I love C programming. How are you doing?
The output of the program will be:
Data from the file: C programming is awesome.
C program that reads a line from a file and displays it:
#include <stdio.h>
int main() {
FILE *fp;
char line[100];
fp = fopen("file.txt", "r");
if (fp) {
fgets(line, 100, fp);
printf("Line read from file: %s", line);
fclose(fp);
} else {
printf("Failed to open file.\n");
}
return 0;
}
Explanation:
#include <stdio.h>
includes the standard input-output header file in our program, which provides input and output operations functionality.int main()
is the entry point of our program.FILE *fp;
declares a file pointer variablefp
that will be used to open and read the file.char line[100];
says a character arrayline
that will be used to store the line read from the file.fp = fopen("file.txt", "r");
opens the file named “file.txt” in read mode and assigns the file pointer tofp
.if (fp) { ... }
checks if the file was opened successfully. If the file was opened successfully, the code inside the curly braces is executed, otherwise, it is skipped.fgets(line, 100, fp);
reads a line from the file usingfgets()
and stores it in theline
array.fgets()
reads at most100
characters (including the newline character) from the file.printf("Line read from file: %s", line);
prints the line read from the file to the console usingprintf()
.fclose(fp);
closes the file.
When we compile and run this program, it will read the first line from the “file.txt” file and display it to the console.