I thought about using a macro to auto close FILE
pointers at the end of a block. My solution so far is:
FILE *fopen_safe(const char *filename, const char *mode) {
FILE *fp = fopen(filename, mode);
if (!fp) {
perror("fopen");
exit(EXIT_FAILURE);
}
return fp;
}
#define with_fopen(fp, filename, mode) \
for (FILE *fp = fopen_safe(filename, mode), _invariant = { ._r = 1 }; _invariant._r--; fclose(fp))
// Usage:
with_fopen(fp, "test", "w") {
fprintf(fp, "test\n");
}
This solution is not elegant as i am using an int in the struct to create my loop invariant.
Is there another way to auto close files? Can a block be associated with a macro in a smarter way?
void *
to fake closures. Not nice, but works unless you're using longjmp. – Daniel Jour Mar 26 at 6:24