Is there a way to get the filename from a `FILE*`? [duplicate]

On some platforms (such as Linux), you may be able to fetch it by reading the link of /proc/self/fd/<number>, as so:

#include <stdio.h>
#include <unistd.h>
#include <string.h>

int main(void)
{
    char path[1024];
    char result[1024];

    /* Open a file, get the file descriptor. */
    FILE *f = fopen("/etc/passwd", "r");
    int fd = fileno(f); 

    /* Read out the link to our file descriptor. */
    sprintf(path, "/proc/self/fd/%d", fd);
    memset(result, 0, sizeof(result));
    readlink(path, result, sizeof(result)-1);

    /* Print the result. */
    printf("%s\n", result);
}

This will, on my system, print out /etc/passwd, as desired.

Leave a Comment