Summary: in this tutorial, you will learn how to read from a text file using standard library functions such as fgetc()
and fgets()
.
Steps for reading from a text file
To read from a text file, you follow these steps:
- First, open the text file using the
fopen()
function. - Second, use the
fgets()
orfgetc()
function to read text from the file. - Third, close the file using the
fclose()
function.
Reading from a text file one character at a time
To read from a text file one character at a time, you use the fgetc() function.
The following program reads from the readme.txt file one character at a time and display the file contents to the output:
#include <stdio.h>
int main()
{
char *filename = "readme.txt";
FILE *fp = fopen(filename, "r");
if (fp == NULL)
{
printf("Error: could not open file %s", filename);
return 1;
}
// read one character at a time and
// display it to the output
char ch;
while ((ch = fgetc(fp)) != EOF)
putchar(ch);
// close the file
fclose(fp);
return 0;
}
Code language: C++ (cpp)
Reading from a text file line by line
To read a line from a text file, you use the fgets() function:
char * fgets ( char *str, int num, FILE *stream );
Code language: C++ (cpp)
The fgets()
function reads characters from the stream
and store them into the str
.
The fgets()
function stops reading if:
- num-1 characters have been read
- the newline character or end-of-file character reached.
Note that the fgets()
function also includes the newline character in the str
.
The following example shows how to use the fgets() function to read a text file line by line and display the text to the output:
#include <stdio.h>
int main()
{
char *filename = "readme.txt";
FILE *fp = fopen(filename, "r");
if (fp == NULL)
{
printf("Error: could not open file %s", filename);
return 1;
}
// reading line by line, max 256 bytes
const unsigned MAX_LENGTH = 256;
char buffer[MAX_LENGTH];
while (fgets(buffer, MAX_LENGTH, fp))
printf("%s", buffer);
// close the file
fclose(fp);
return 0;
}
Code language: C++ (cpp)
Summary
- Use the
fgetc()
function to read from a text file, a character at a time. - Use the
fgets()
function to read from a text file, line by line.