C File Handling
| Function | Purpose |
|---|---|
fopen(name, mode) | Open a file ("r", "w", "a", "r+", "rb" …) |
fprintf / fscanf | Formatted write / read |
fputc / fgetc | Character write / read |
fgets / fputs | Line read / write |
fclose(fp) | Close the file |
#include <stdio.h>
int main() {
FILE *fp = fopen("data.txt", "w");
if (fp == NULL) { printf("Cannot open file\n"); return 1; }
fprintf(fp, "Roll: %d\nName: %s\n", 7, "Ravi");
fclose(fp);
char line[100];
fp = fopen("data.txt", "r");
while (fgets(line, sizeof line, fp) != NULL)
printf("%s", line);
fclose(fp);
return 0;
}
Roll: 7
Name: Ravi
Track your progress through the C course