Reading files in C involves using the file handling functions provided by the standard I/O library. Here's a simple explanation with an example:
#include <stdio.h>
int main() {
FILE *filePointer; // Declare a file pointer
char buffer[100]; // Buffer to store read content
// Open file in read mode
filePointer = fopen("example.txt", "r");
// Check if file was successfully opened
if (filePointer == NULL) {
printf("Unable to open file.\n");
return 1; // Exit program with error
}
// Read content from the file using fgets() function
while (fgets(buffer, sizeof(buffer), filePointer) != NULL) {
printf("%s", buffer); // Print each line
}
// Close the file
fclose(filePointer);
return 0;
}
In this example
stdio.h
header file to use file handling functions.filePointer
.buffer
to store the content read from the file.fopen()
function to open a file named "example.txt"
in read mode ("r"
).fopen()
returns NULL
, it means the file could not be opened, so we print an error message and exit the program.fgets()
function. The fgets()
function reads a line from the file into the buffer. The loop continues until fgets()
returns NULL
, indicating the end of the file.printf()
.fclose()
function to free up system resources.When you run this program, it will open the file named "example.txt"
in the current directory (where the executable is located), read its content line by line, and print each line to the console.