Reading text files is a fundamental skill in C programming. Whether you need to process data from log files, configuration files, or other text-based sources, knowing how to read text files is crucial. In this beginner’s guide, we will explore the basics of reading text files in C.

Accelerate your tech career
with hands-on learning.
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial
get the skills and confidence to land your next move.
This C program reads the contents of a file named “memo.txt” and prints them to the console, providing a straightforward example of how to read the contents of a file in C.
#include <stdio.h>
#define BUFSIZE 100
int main() {
// declare buffer to hold line of text read from file
char line[BUFSIZE];
// specify name of file to be read
char* filename = "memo.txt";
/* open the specified file in read mode 'r' */
FILE* fptr = fopen(filename, "r");
// check if file was opened successfully
if(fptr == NULL)
{
printf("Could not open file '%s' for reading.\n", filename);
return 1;
}
// loop through file until end of file is reached
while(!feof(fptr)) {
// read a line of text from the file into the buffer
fgets(line, BUFSIZE, fptr);
// print out the read text to the console
printf("%s", line);
}
/* close the file */
fclose(fptr);
printf("\nFile '%s' was read successfully.\n", filename);
return 0;
}
I sincerely hope that you find this code helpful. If you wish to learn more about C, please subscribe to our newsletter today and continue your C learning journey with us!