How do I find a filename, given a FILE pointer?

Check out this answer to obtain file descriptor and this answer to get file name from file descriptor. Should be OK on Linux (not sure about other operating systems).

Here's a quick working example (tested under Cygwin/Win7):

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

int main()
{
    int MAXSIZE = 0xFFF;
    char proclnk[0xFFF];
    char filename[0xFFF];
    FILE *fp;
    int fno;
    ssize_t r;

    // test.txt created earlier
    fp = fopen("test.txt", "r");
    if (fp != NULL)
    {
        fno = fileno(fp);
        sprintf(proclnk, "/proc/self/fd/%d", fno);
        r = readlink(proclnk, filename, MAXSIZE);
        if (r < 0)
        {
            printf("failed to readlink\n");
            exit(1);
        }
        filename[r] = '\0';
        printf("fp -> fno -> filename: %p -> %d -> %s\n",
                fp, fno, filename);
    }
    return 0;
}

Output:

fp -> fno -> filename: 0x80010294 -> 3 -> /tmp/test.txt

This can be done in 2 stages. First, you will need to get the file descriptor, then you will need to recover the filename. The following is an example, but has some serious buffer overflow vulnerabilities!

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

char * recover_filename(FILE * f) {
  int fd;
  char fd_path[255];
  char * filename = malloc(255);
  ssize_t n;

  fd = fileno(f);
  sprintf(fd_path, "/proc/self/fd/%d", fd);
  n = readlink(fd_path, filename, 255);
  if (n < 0)
      return NULL;
  filename[n] = '\0';
  return filename;
}

Tags:

C

File