C reading and writing text files
C reads and writes files through a FILE pointer. fopen opens a file in a mode such as "w+" for writing and reading, fprintf writes formatted text, rewind moves back to the start, and fgets reads one line at a time into a buffer of a given size. fclose flushes and releases the file.
C
#include <stdio.h>
int main(void) {
FILE *file = fopen("lesson_data.txt", "w+");
if (file == NULL) {
printf("could not open the file\n");
return 1;
}
fprintf(file, "alpha 3\nbeta 5\ngamma 8\nbad line\n");
rewind(file);
char line[64];
int total = 0;
int good = 0;
while (fgets(line, sizeof line, file) != NULL) {
char name[32];
int value;
if (sscanf(line, "%31s %d", name, &value) == 2) {
printf("%s -> %d\n", name, value);
total += value;
good++;
} else {
printf("skipped a malformed line\n");
}
}
fclose(file);
remove("lesson_data.txt");
printf("%d good lines, total %d\n", good, total);
return 0;
}