To read a file in C, you can use standard library functions like fopen(), fgetc(), fgets(), or fread() depending on the type of data you want to read. Below, I’ll explain and provide examples of how to read a file in C using these functions.
Read a File in C
- Open the file using fopen().
- Read the file using one of the reading functions (fgetc(), fgets(), fread()).
- Close the file using fclose() when done.
fgetc() Method (Read Character by Character)
fgetc() reads a single character from a file. It returns the character read as an int (or EOF if the end of file is reached). It reads one character at a time from the file.
Example:
#include <stdio.h>
int main() {
FILE *file = fopen("main.txt", "r");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
char ch;
// Read and print each character until EOF
while ((ch = fgetc(file)) != EOF) {
putchar(ch); // Print the character
}
fclose(file); // Close the file
return 0;
}
fgets() Method (Read Line by Line)
fgets() reads a line of text from a file, including spaces, and stores it in a string (character array). It stops when either the maximum number of characters is reached or a newline (\n) is encountered. It reads an entire line (up to a specified size) from the file.
Example:
#include <stdio.h>
int main() {
FILE *file = fopen("main.txt", "r");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
char buffer[350];
// Read and print each line
while (fgets(buffer, sizeof(buffer), file) != NULL) {
printf("%s", buffer); // Print the line
}
fclose(file); // Close the file
return 0;
}
fread() Method (Read Binary Data)
fread() is used to read binary data from a file into a buffer. It is useful for reading non-text files (e.g., images, audio, etc.) or large chunks of data at once.
Example:
#include <stdio.h>
int main() {
FILE *file = fopen("main.txt", "r");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
// Read the file in chunks (size of each chunk is 100 bytes)
char buffer[350];
size_t bytesRead;
while ((bytesRead = fread(buffer, 1, sizeof(buffer), file)) > 0) {
// Print the contents as characters (assuming text file)
for (size_t i = 0; i < bytesRead; i++) {
putchar(buffer[i]);
}
}
fclose(file); // Close the file
return 0;
}
Read a file in C – Questions and Answers
Q 1: Which functions are used to read a file?
Ans: fscanf(), fgets(), fgetc().
Q 2: What does fgets() do?
Ans: Reads a line from a file.
Q 3: How do you check end-of-file?
Ans: Using feof().
Q 4: What happens if file does not exist in read mode?
Ans: fopen() returns NULL.
Q 5: Why is file closing important?
Ans: To release resources and save changes.
C read a file – Objective Questions (MCQs)
Q1. Which function is used to read a character from a file?
Q2. What does the following code do?
FILE *fp = fopen("data.txt", "r");
Q3. What does fgets() do in C?
Q4. What will happen if the file does not exist in "r" mode?
Q5. Which function can be used to read formatted data from a file?