C Intermediate
File Operations (I/O) in C
C represents files as streams of characters. File operations require using the FILE structure defined in <stdio.h>.
1. Opening and Closing Files
Use fopen() to open a stream and fclose() to release the system file handle:
FILE *fptr = fopen("data.txt", "w"); // Mode "w" opens file for writing (overwrites)
if (fptr == NULL) {
// Always check for NULL pointer in case of file open failures
}
fclose(fptr);
Common modes:
- "r": Read mode. File must exist.
- "w": Write mode. Creates file or truncates/overwrites if it exists.
- "a": Append mode. Writes data at the end of the file.
2. Reading and Writing Text Files
fprintf(file, ...): Writes formatted text output to a file stream.fscanf(file, ...): Reads formatted data input from a file stream.fgets(buffer, size, file): Reads a full line of text safely.
#include <stdio.h>
int main() {
// Writing data
FILE *write_ptr = fopen("score.txt", "w");
if (write_ptr != NULL) {
fprintf(write_ptr, "Highscore: %d\n", 950);
fclose(write_ptr);
}
// Reading data
FILE *read_ptr = fopen("score.txt", "r");
if (read_ptr != NULL) {
char line[50];
if (fgets(line, sizeof(line), read_ptr) != NULL) {
printf("Read from file: %s", line);
}
fclose(read_ptr);
}
return 0;
}
3. Binary File Operations
For raw data blocks (like arrays or structs), use binary mode ("wb", "rb") with:
- fwrite(ptr, size, count, file): Writes block to file.
- fread(ptr, size, count, file): Reads block from file.