IntermediateLesson 12 of 18
Files & Error Handling – C
Reading and writing files with stdio, checking return codes, errno and cleaning up with goto.
You open files with fopen (mode "r", "w", "a", each optionally with b for binary). It returns a FILE *, or NULL on errors. Always call fclose when you are done.
#include <stdio.h>
int main(void) {
FILE *out = fopen("zahlen.txt", "w");
if (out == NULL) { perror("fopen"); return 1; }
for (int i = 1; i <= 5; i++) fprintf(out, "%d\n", i * 10);
fclose(out);
FILE *in = fopen("zahlen.txt", "r");
if (in == NULL) { perror("fopen"); return 1; }
int x, summe = 0;
while (fscanf(in, "%d", &x) == 1) summe += x;
fclose(in);
printf("Sum: %d\n", summe); // 150
return 0;
}C has no exceptions. You report errors via return values (NULL, -1, 0 for success) and the global variable errno. strerror(errno) and perror turn it into readable text. With strtol, errno is especially important, because the return value alone reveals nothing:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
// 0 = success, -1 = error. The result comes back through the pointer.
int lese_zahl(const char *text, long *ergebnis) {
char *ende;
errno = 0;
long v = strtol(text, &ende, 10);
if (errno != 0 || ende == text || *ende != '\0') return -1;
*ergebnis = v;
return 0;
}
int main(void) {
const char *eingaben[] = {"123", "12x", "", "-7"};
for (int i = 0; i < 4; i++) {
long z;
if (lese_zahl(eingaben[i], &z) == 0) printf("\"%s\" -> %ld\n", eingaben[i], z);
else printf("\"%s\" invalid\n", eingaben[i]);
}
FILE *f = fopen("/does/not/exist", "r");
if (f == NULL) perror("Opening failed");
return 0;
}When a function acquires several resources (file, memory, ...), goto cleanup leads to tidy cleanup in exactly one place. This is one of the few accepted uses of goto in C:
#include <stdio.h>
#include <stdlib.h>
int verarbeite(const char *pfad) {
int status = -1;
FILE *f = NULL;
char *puffer = NULL;
f = fopen(pfad, "r");
if (f == NULL) goto ende;
puffer = malloc(1024);
if (puffer == NULL) goto ende;
if (fgets(puffer, 1024, f) != NULL) printf("First line: %s", puffer);
status = 0;
ende:
free(puffer); // free(NULL) is allowed
if (f != NULL) fclose(f);
return status;
}
int main(void) {
printf("Status: %d\n", verarbeite("/does/not/exist")); // -1
return 0;
}WarningCheck every return value that can report errors:
fopen, malloc, scanf, fgets, fclose (for files you wrote to!). An ignored error later turns into an inexplicable crash somewhere entirely different.Tip
errno is only meaningful directly after a failed call – every successful call is allowed to change it. Set it to 0 before strtol and the like, and read it immediately afterwards.