C File Handling
C programs can read from and write to files using the <stdio.h> file functions, centered around the FILE pointer type. fopen() opens a file, and fclose() closes it when finished.
Common operations include fprintf()/fscanf() for formatted text, and fgets()/fputs() for reading and writing lines of text.
FILE *f = fopen("file.txt", "w");
fclose(f);Opening and closing files
fopen("name", "mode") opens a file in a mode like "r" (read), "w" (write, overwrites), or "a" (append), and returns a FILE* (or NULL on failure). Always call fclose() when done.
Reading and writing
fprintf(file, ...) writes formatted text to a file just like printf does to the screen. fgets(buffer, size, file) reads a line of text into a buffer safely.
#include <stdio.h>
int main() {
FILE *f = fopen("out.txt", "w");
if (f != NULL) {
fprintf(f, "Hello, file!\n");
fclose(f);
}
return 0;
}(creates out.txt containing: Hello, file!)The file is opened for writing, written to, then closed.
#include <stdio.h>
int main() {
FILE *f = fopen("out.txt", "r");
char line[100];
if (f != NULL) {
fgets(line, 100, f);
printf("%s", line);
fclose(f);
}
return 0;
}Hello, file!fgets reads a line from the opened file into the buffer, which is then printed.
Key points
- fopen() opens a file and returns a FILE pointer (or NULL on failure).
- Common modes are "r" (read), "w" (write/overwrite), and "a" (append).
- Always check for NULL and call fclose() when finished with a file.
- fprintf/fscanf and fgets/fputs handle formatted and line-based I/O.
