Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find a filename, given a FILE pointer? [duplicate]

Tags:

c

file

Possible Duplicate:
Getting Filename from file descriptor in C
Obtain filename from file pointer in C

I have a function here:

handle_file(FILE *file)
{
    if(condition)
    {
        print filename and other msg;
    }
}

The only thing we know here is the a pointer to the file; is it possible to get the filename according to the pointer?

like image 567
nzomkxia Avatar asked Jun 27 '12 07:06

nzomkxia


2 Answers

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
like image 118
bcelary Avatar answered Sep 23 '22 02:09

bcelary


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;
}
like image 42
Alex Chamberlain Avatar answered Sep 20 '22 02:09

Alex Chamberlain