Overloading open() and fopen()

One can overload fopen() and open() for debugging purpose, the example below traces each file opening operation:

#include 
#include 
static FILE * (*next_fopen)(const char *path, const char *mode);

FILE * fopen(const char *path, const char *mode) {
    char *msg;

    if (next_fopen == NULL) {
        next_fopen = dlsym(RTLD_NEXT, "fopen");
        if ((msg = dlerror()) != NULL)
            printf("**fopen dlopen failed : %s\n", msg);
    }

    printf("*fopen : %s\n", path);
    return next_fopen(path, mode);
}

static int (*next_open)(const char *path, int oflag, ...);

int open(const char *path, int oflag, ...) {
    char *msg;

    if (next_open == NULL) {
        next_open = dlsym(RTLD_NEXT, "open");
        if ((msg = dlerror()) != NULL)
            printf("**open dlopen failed : %s\n", msg);
    }

    printf("*open : %s\n", path);
    va_list args;
    va_start(args, path);
    mode_t mode = va_arg(args, mode_t);
    int fd = next_open(path, oflag, mode); // handle vararg
    va_end(args);
    return fd;
}
This entry was posted in programming. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *