Python style with-statement in C 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?
There are few problems with this macro.


It relies on an undocumented layout of FILE structure
It cannot be nested (try it with -Wshadow)
It assumes that the block is always left through the end
It may create suprises:

    for (....) {
        with_fopen(fp, ...) {
            int rc = do_something(fp);
            if (rc == -1) {
                break;
            }
        }
    }


The programmer (with or without Python background) expects the outer loop to be broken. Instead the loop hidden inside with is.


Nice try however.