Write a C program to read a file and display its contents on console. How to read a file and display file contents on console in C programming. In this exercises, I will explain you how to read a file character by character using fgetc()
. How to read a file line by line using fgets()
.
Required knowledge
Basic Input Output, Do while loop, While loop, Pointers, File Handling
In the previous post, I explained how to use FILE
pointer, fopen()
, fputs()
and fclose()
function to create and write data into file.
In this post, we will continue further and will learn various functions in C programming to read and display file contents on console.
How to read data from a file?
C programming supports four predefined functions fgetc()
, fgets()
, fscanf()
and fread()
to read data from file. These functions are defined in stdio.h
header file.
fgetc()
– Used to read single character from file.
fgets()
– Used to read string from file.
fscanf()
– Use this to read formatted input from file.
fread()
– Read block of raw bytes from file. Used to read binary files.
Step by step descriptive logic to read a file and display file contents.
- Open a file using
fopen()
function and store its reference in aFILE
pointer say fPtr.You must open file in r(read) mode or atleast mode that support read access.
- Read content from file using any of these functions
fgetc()
,fgets()
,fscanf()
orfread()
. - Finally, close the file using
fclose(fPtr)
.
In this post I will explain how to read a file using fgetc()
and fgets()
. I will explain separately how to read formatted input and binary files.
How to read a file character by character using fgetc()?
int fgetc(FILE * stream);
- The function accepts pointer to
FILE
type, source stream to read. - On each successful read it return character (ASCII value) read from stream and advance read position to next character.
It returns a constant EOF (-1) on unsuccessful read or if there is no more content to read.
Program to read a file character by character using fgetc()?
/**
* C program to read a file and display file contents character by character using fgetc()
*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
/* File pointer to hold reference to our file */
FILE * fPtr;
char ch;
/*
* Open file in r (read) mode.
* "data/file1.txt" is complete file path to read
*/
fPtr = fopen("data/file1.txt", "r");
/* fopen() return NULL if last operation was unsuccessful */
if(fPtr == NULL)
{
/* Unable to open file hence exit */
printf("Unable to open file.\n");
printf("Please check whether file exists and you have read privilege.\n");
exit(EXIT_FAILURE);
}
/* File open success message */
printf("File opened successfully. Reading file contents character by character. \n\n");
do
{
/* Read single character from file */
ch = fgetc(fPtr);
/* Print character read on console */
putchar(ch);
} while(ch != EOF); /* Repeat this if last read character is not EOF */
/* Done with this file, close file to release resource */
fclose(fPtr);
return 0;
}
Suppose data/file1.txt
contains
Hurray!!! I learned to create file in C programming. I also learned to write contents to file. Next, I will learn to read contents from file on Codeforwin. Happy coding ;)
Output
File opened successfully. Reading file contents character by character. Hurray!!! I learned to create file in C programming. I also learned to write contents to file. Next, I will learn to read contents from file on Codeforwin. Happy coding ;)
How to read a file line by line using fgets()?
char * fgets(char * str, int num, FILE * stream);
- It accepts three parameters among which str is pointer to character. On success str points to string read from given stream.
- Next, num is maximum characters to read from stream.
- stream is a pointer to
FILE
type specifying input stream to read. - On success the function sets str to point to character read and return the same str. On failure it sets str to
NULL
pointer and returnNULL
pointer.
Program to read a file line by line using fgets()
/**
* C program to read a file and display file contents line by line using fgets()
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 1000
int main()
{
/* File pointer to hold reference to our file */
FILE * fPtr;
char buffer[BUFFER_SIZE];
int totalRead = 0;
/*
* Open file in r (read) mode.
* "data/file2.txt" is complete file path to read
*/
fPtr = fopen("data/file2.txt", "r");
/* fopen() return NULL if last operation was unsuccessful */
if(fPtr == NULL)
{
/* Unable to open file hence exit */
printf("Unable to open file.\n");
printf("Please check whether file exists and you have read privilege.\n");
exit(EXIT_FAILURE);
}
/* File open success message */
printf("File opened successfully. Reading file contents line by line. \n\n");
/* Repeat this until read line is not NULL */
while(fgets(buffer, BUFFER_SIZE, fPtr) != NULL)
{
/* Total character read count */
totalRead = strlen(buffer);
/*
* Trim new line character from last if exists.
*/
buffer[totalRead - 1] = buffer[totalRead - 1] == '\n'
? '\0'
: buffer[totalRead - 1];
/* Print line read on cosole*/
printf("%s\n", buffer);
}
/* Done with this file, close file to release resource */
fclose(fPtr);
return 0;
}
Suppose data/file2.txt
contains
Reading a file line by line.
--------------------------------------------
I love programming in C.
Learning programming on Codeforwin is easy.
Output
File opened successfully. Reading file contents line by line. Reading a file line by line. -------------------------------------------- I love programming in C. Learning programming on Codeforwin is easy.
Recommended programs to practice
- File handling exercises index.
- C program to create a file and write data into file.
- C program to read numbers from a file and write even, odd and prime numbers in separate file.
- C program to append data into a file.
- C program to compare two files.
- C program to copy contents from one file to another file.
- C program to read and merge two files in single file.
Happy coding 😉