File Input & Output (I/O)
C communicates with storage drives via file streams. Files are opened, modified, and closed using standard stream declarations.
1 File pointers and Modes (`FILE*`)
C represents file streams using the `FILE` structure pointer. Common access modes include:
- `"r"`: Read mode. Fails if the file does not exist.
- `"w"`: Write mode. Overwrites the file contents or creates a new file.
- `"a"`: Append mode. Appends new data to the end of the existing file.
2 Writing and Reading Files
Let's run a program that writes data to a text file and then reads it back to display on the screen:
C — File Handling
▶ Run Code
#include <stdio.h>
int main() {
// Open stream in write mode
FILE *file = fopen("example.txt", "w");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
// Write text to file stream
fprintf(file, "Learning C File Operations!\n");
fclose(file); // Always close the stream
// Open stream in read mode
file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
char buffer[100];
// Read formatted lines from stream
while (fgets(buffer, sizeof(buffer), file) != NULL) {
printf("File Content: %s", buffer);
}
fclose(file);
return 0;
}
3 Code Challenge
Challenge: Write a program that writes three lines containing the numbers `100`, `200`, and `300` to a text file. Open the file in read mode, parse the integers, compute their sum, and print the final sum to the console.