C Program to print contents of file
Last Updated :
22 Aug, 2024
In C, reading the contents of a file involves opening the file, reading its data, and then processing or displaying the data.
Example
Input: File containing “This is a test file.\nIt has multiple lines.”
Output: This is a test file.
It has multiple lines.
Explanation: The program reads and displays the multiline text from the file.
In this article, we will learn different methods to read the content of the whole file in C using file handling.
How to Read a File in C?
In C, 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. The following are the steps that show how to read a file in C:
- Opening the File: We first need to connect the file with the current C program by telling its location in the memory and selecting the type of operation (mode) we will do on it. This can be done with the help of fopen() function.
- Reading the Data: We can start reading the data after opening the file. The file must be opened in the read mode to read data. We can use the methods discussed below to read the file according to our requirements.
- Closing the File: After all the operations are done, it is a good practice to close the file using fclose() function to free the acquired memory.
Different Methods to Read a File in C
C programming language supports four pre-defined functions to read contents from a file, all of which are defined in <stdio.h> header:
1. Using fgetc()
fgetc() functions reads a single character pointed by the file pointer. On each successful read, it returns the character (ASCII value) read from the stream and advances the file pointer to the next character. It returns a constant EOF (-1) when there is no content to read or an unsuccessful read.
We can read the whole content of the file using this function by reading characters one by one till we encounter NULL:
Syntax of fgetc()
fgetc(file_ptr);
Program to Read a File using fgetc()
C
// C program to read a file using fgetc()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
// Opening file
FILE *file_ptr;
// Character buffer that stores the read character
// till the next iteration
char ch;
// Opening file in reading mode
file_ptr = fopen("test.txt", "r");
if (NULL == file_ptr) {
printf("file can't be opened \n");
return EXIT_FAILURE;
}
printf("Content of the file are:-: \n");
// Printing what is written in file
// character by character using loop.
while ((ch = fgetc(file_ptr)) != EOF) {
printf("%c", ch);
}
// Closing the file
fclose(file_ptr);
return 0;
}
test.txt
GeeksforGeeks | A computer science portal for geeks
Output:
Content of the file are:-
GeeksforGeeks | A computer science portal for geeks
When to use fgetc()?
Reading file using fgetc() is useful for processing each character individually, such as counting specific characters or handling text encoding. It is also useful to print data when you don’t know anything about the file.
2. Using fgets()
The fgets() function is similar to the fgetc() but instead of a single character, it reads one string at a time. It returns the string if it is successfully read or returns NULL if failed.
Syntax of fgets()
fgets(str, size, file_ptr);
where,
- str: It is string in which fgets() store string after reading it from file.
- size: It is maximum characters to read from stream.
- file_ptr: It is file pointer.
Program to Read a File using fgets()
C
// C Program to Read a File using fgets()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
// Defining file pointer and opening the file.
FILE *file_ptr;
char str[50];
// a+ Mode Means that the file is opened in the
// append + reading mode
file_ptr = fopen("test.txt", "r");
if (NULL == file_ptr) {
printf("File can't be opened \n");
}
// Reading stinrg using fgets
printf("Content of this file are:: \n");
while (fgets(str, 50, file_ptr) != NULL) {
printf("%s", str);
}
fclose(file_ptr);
return 0;
}
test.txt
GeeksforGeeks | A computer science portal for geeks
Output
Content of this file are::
GeeksforGeeks | A computer science portal for geeks
When to use fgets()?
Reading file using fgets() is ideal for text files where lines need to be processed individually, such as reading configuration files or log files.
fscanf() is similar to scanf() that reads the input in the form of formatted string. It can take, ignore, modify the types of the variables using the scanset characters.
Syntax
int fscanf(FILE *ptr, const char *format, ...)
Program to Read a File Using fscanf()
C
// C Program to Read a File Using fscanf()
#include <stdio.h>
int main() {
FILE *ptr = fopen("test.txt", "r");
if (ptr == NULL) {
printf("no such file.");
return 0;
}
/* Assuming that test.txt has content
in below format
NAME AGE
Raman 12
Kunal 25
Vikas 65 */
char name[100];
int age;
printf("Contents of the File are:\n");
while (fscanf(ptr, "%s %d", name, &age) == 2) {
printf("Name: %s\t Age: %d\n", name, age);
}
return 0;
}
test.txt
Raman 12
Kunal 25
Vikas 65
Output
Contents of the File are:
Name: Raman Age: 12
Name: Kunal Age: 25
Name: Vikas Age: 65
When to use fscan()?
Reading a file using fread() is best for structured data files, such as CSV files or files with fixed formats (e.g., reading a list of records with specific fields).
4. Using fread()
fread() makes it easier to read blocks of data from a file. For instance, in the case of reading a structure from the file, it becomes an easy job to read using fread because instead of looking for types, it reads the blocks of data from the file in the binary form.
Syntax of fread()
size_t fread(buffer_ptr, size, nmemb, file_ptr)
where,
- buffer_ptr: This is the pointer to a block of memory with a minimum size of size*nmemb bytes.
- size: This is the size in bytes of each element to be read.
- nmemb: This is the number of elements, each one with a size of size bytes.
- file_ptr: This is the pointer to a FILE object that specifies an input stream.
If the value of size or count is equal to zero, then this program will simply return 0.
Program to Read a File in C Using fread()
C
// C Program to Read a File in C Using fread()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Example Structure
struct Course {
int price;
char cname[100];
};
int main() {
// Writing data to the binary file
FILE *file_ptr;
file_ptr = fopen("test.bin", "wb");
if (file_ptr == NULL) {
fprintf(stderr, "\nError to open the file\n");
exit(1);
}
struct Course var1;
strcpy(var1.cname, "Data Structures and Algorithms - Self Paced");
var1.price = 6000;
fwrite(&var1, sizeof(var1), 1, file_ptr);
fclose(file_ptr);
// File pointer to read from file
file_ptr = fopen("test.bin", "rb");
if (file_ptr == NULL) {
fprintf(stderr, "\nError to open the file\n");
exit(1);
}
// Structure variable to store the data read
struct Course inp;
// Start reading the data using fread
while (fread(&inp, sizeof(struct Course), 1, file_ptr)) {
printf("Course Name = %s Price = %d\n", inp.cname, inp.price);
}
fclose(file_ptr);
}
test.txt
// Binary form of structure
Output
Course Name = Data Structures and Algorithms - Self Paced Price = 6000
When to use fread()?
Reading a file using fread() is suitable for binary files or when you need to manipulate the entire file content at once, such as image files or raw data files.
Frequently Asked Questions on Reading Files in C – FAQs
What is the difference between fgets() and fgetc()?
fgets() reads a whole line from the file at once, while fgetc() reads one character at a time.
How is fscanf() different from fgets()?
fscanf() reads formatted input, making it ideal for structured data, whereas fgets() reads raw strings, usually one line at a time.
Why is it important to close a file after reading it in C?
Closing a file using fclose() is important to free up resources and avoid memory leaks in your program.
Can I use these methods interchangeably?
Yes, you can use these methods to read files interchangeably, but each is suited for different scenarios, so it’s best to choose the one that matches your file type and data processing needs.