Reading from files lets your program get information saved on your computer. This helps your program use data that was saved before or from other sources.
0
0
Reading from files in C
Introduction
You want to load a list of names saved in a file to use in your program.
You need to read settings or preferences stored in a file to customize your program.
You want to process a text file with data like scores or messages.
You want to read a log file to check what happened earlier.
You want to read a file that a user selects to show its content.
Syntax
C
FILE *file_pointer; file_pointer = fopen("filename.txt", "r"); if (file_pointer == NULL) { // handle error } // read from file fclose(file_pointer);
fopen opens the file. The "r" means open for reading.
Always check if fopen returns NULL. That means the file could not be opened.
Examples
Open a file named data.txt for reading and check if it opened successfully.
C
FILE *fp = fopen("data.txt", "r"); if (fp == NULL) { printf("Cannot open file\n"); }
Read the file line by line and print each line.
C
char line[100]; while (fgets(line, sizeof(line), fp)) { printf("%s", line); }
Read the file character by character and print each character.
C
int c; while ((c = fgetc(fp)) != EOF) { putchar(c); }
Sample Program
This program opens a file named example.txt for reading. It reads the file line by line and prints each line to the screen. If the file cannot be opened, it prints an error message.
C
#include <stdio.h> int main() { FILE *file = fopen("example.txt", "r"); if (file == NULL) { printf("Failed to open file.\n"); return 1; } char line[256]; while (fgets(line, sizeof(line), file)) { printf("%s", line); } fclose(file); return 0; }
OutputSuccess
Important Notes
Remember to close the file with fclose() to free resources.
fgets() reads one line at a time including the newline character.
Use fgetc() to read one character at a time if needed.
Summary
Use fopen() with "r" to open a file for reading.
Check if the file opened successfully by testing if the pointer is NULL.
Read file content using fgets() for lines or fgetc() for characters.