C Program to Print Contents of File
Last Updated :
07 Jan, 2025
C language allows users to process the files in its programs. Reading a file is a step-by-step process in which we first have to prepare the file only after which we can start reading. In this article, we will learn how to read and print the contents of a file using C program.
The simplest method to print the whole contents of a file is by using the fgetc() function to read and print each character one by one till the end of the file is reached. Let's take a look at an example:
C
#include <stdio.h>
int main() {
// Open file in read mode
FILE *fptr = fopen("file.txt", "r");
// Check if the file was opened successfully
if (fptr == NULL) {
return 1;
}
// Read and print each character from the file
char ch;
while ((ch = fgetc(fptr)) != EOF) {
putchar(ch);
}
// Close the file after reading
fclose(fptr);
return 0;
}
Assuming the contents of file.txt are:
Hello, Geeks!
This is a test file.
The output will be:
Hello, Geeks!
This is a test file.
Explanation: The program opens the file file.txt in read mode ("r") using fopen(). If the file cannot be opened, fopen() returns NULL and the execution is stopped. Else, it reads the file by one character at a time using fgetc() in a loop, printing each character until fgetc() returns EOF indicating that the whole file is read. Finally, the file is closed using fclose().
Apart from the getc() function, C also provides other methods to print the contents of a file, though, the other steps remain same. Some of them are as follows:
Using fgets()
The fgets() function is a good choice to print the file line by line. This function reads the given number of characters from the file and stores it in a buffer. This buffer can be then printed after each read and then be used to read the next line.
C
#include <stdio.h>
int main() {
FILE *fptr = fopen("file.txt", "r");
if (fptr == NULL) {
return 1;
}
// Read and print each line from the file
char buff[100];
while (fgets(buff, sizeof(buff), fptr) != NULL) {
printf("%s", buff);
}
fclose(fptr);
return 0;
}
Output
Hello, Geeks!
This is a test file.
Explanation: In this program, fgets() is used to read one line at a time from the file file.txt. It stores the read content into the buff array, up to 99 characters, and includes the newline character if present. The function ensures safe reading by limiting the number of characters and appends a null terminator '\0' at the end of each line.
Using fread()
The fread()function can read blocks of data from a file. It is generally preferred for binary files but can also be used to read the text files.
C
#include <stdio.h>
int main() {
FILE *fptr = fopen("file.txt", "r");
if (fptr == NULL) {
return 1;
}
// Read and print each block of data from the file
char buff[100];
size_t n;
while ((n = fread(buff, sizeof(char), sizeof(buff) - 1, fptr)) > 0) {
// Manually have to NULL terminate buffer
buff[n] = '\0';
printf("%s", buff);
}
fclose(fptr);
return 0;
}
Output
Hello, Geeks!
This is a test file.
Explanation: In this program, fread() is used to read raw data from the file file.txt in blocks of up to 99 bytes (or character as each character is 1 byte). The function returns the number of characters successfully read, but we manually add a null terminator (\0) to the buffer after each read to ensure the string is properly formatted for printing.
Similar Reads
Basics of File Handling in C File handling in C is the process in which we create, open, read, write, and close operations on a file. C language provides different functions such as fopen(), fwrite(), fread(), fseek(), fprintf(), etc. to perform input, output, and many different C file operations in our program.Need of File Han
13 min read
C fopen() Function In C, the fopen() function is used to open a file in the specified mode. The function returns a file pointer (FILE *) which is used to perform further operations on the file, such as reading from or writing to it. If the file exists then the fopen() function opens the particular file else a new file
5 min read
EOF, getc() and feof() in C In this article, we will discuss the EOF, getc() function and feof() function in C.What is EOF?In C, EOF is a constant macro defined in the <stdlib.h> header file that is used to denote the end of the file in C file handling. It is used by various file reading functions such as fread(), gets()
3 min read
fgets() in C In C, fgets() is a built-in function defined in <stdio.h> header file. It reads the given number of characters of a line from the input stream and stores it into the specified string. This function stops reading the characters when it encounters a newline character, has read the given number o
3 min read
fprintf() in C fprintf is used to print content in file instead of stdout console. int fprintf(FILE *fptr, const char *str, ...); Example: C // C Program for the above approach #include<stdio.h> int main() { int i, n=2; char str[50]; //open file sample.txt in write mode FILE *fptr = fopen("sample.txt
1 min read
scanf() and fscanf() in C In C language, scanf() function is used to read formatted input from stdin. It returns the whole number of characters written in it otherwise, returns a negative value.Syntax:int scanf(const char *characters_set)Time Complexity: O(n)Auxiliary Space: O(n) where n is the length of input.Many of us kno
4 min read
C fread() Function The C fread() is a standard library function used to read the given amount of data from a file stream. Defined inside <stdio.h>, the fread() function reads the given number of elements of specific size from the file stream and stores it in the buffer memory. The total number of bytes read by f
4 min read
fseek() vs rewind() in C In C, the functions fseek() and rewind() helps in manipulating the position of the pointer in the opened file but serve different purposes and have distinct working. The below table lists the major differences between fseek() and rewind() in C:Featurefseek()rewind()FunctionalityMoves the file pointe
2 min read
What is return type of getchar(), fgetc() and getc() ? In C, getchar(), fgetc(), and getc() all are the functions used for reading characters from input buffer. This buffer is standard input buffer for getchar() and can be any specified file for getc() and fgetc(). In this article, we will learn about the return type of these functions and why it matter
3 min read
Read/Write Structure From/to a File in C For writing in the file, it is easy to write string or int to file using fprintf and putc, but you might have faced difficulty when writing contents of the struct. fwrite and fread make tasks easier when you want to write and read blocks of data.Writing Structure to a File using fwriteWe can use fwr
3 min read