Read Files in C
? Reading Files in C
In C, reading files is done using functions from the <stdio.h> library. You open a file with fopen(), read it using fgetc(), fgets(), or fread(), and always close it with fclose().
? Steps to Read a File
Include header:
#include <stdio.h>Open file in read mode:
"r"Read content using a suitable function
Close the file
? Example: Read File Line-by-Line
#include <stdio.h>int main() { FILE *file; char line[256]; file = fopen("myfile.txt", "r"); if (file == NULL) { printf("Could not open file.\n"); return 1; } while (fgets(line, sizeof(line), file)) { printf("%s", line); } fclose(file); return 0;}
? Other File Reading Functions
| Function | Description |
|---|---|
fgetc() | Reads one character at a time |
fgets() | Reads a line (or string) |
fread() | Reads block of binary data |
? Example: Read Character-by-Character
FILE *f = fopen("file.txt", "r");char ch;while ((ch = fgetc(f)) != EOF) { putchar(ch);}fclose(f);
?? Always Check
Make sure the file exists before reading.
Always check if
fopen()returnsNULL.Don't forget to
fclose()when done.