How to find a file name given a FILE pointer?

Possible duplicate:
Getting file name from file descriptor in C
Get file name 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 a file pointer; Is it possible to get the file name according to the pointer?

+6
source share
5 answers

Check this answer to get the file descriptor and this answer to get the file name from the file descriptor. It should be good on Linux (not sure about other operating systems).

Here is a quick working example (tested in 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; } 

Conclusion:

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

This can be done in 2 steps. First, you will need to get the file descriptor, then you will need to restore the file name. The following is an example, but there are 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; } 
+2
source

When I searched if you are the root and the lsof command exists on your system, you can use fileno(fp) to get the descriptor of the initial lsof -d descriptor file. You may try.

0
source

Otherwise, you can use opendir and struct dirent if you want to parse the entire directory and files in a folder. This does not use a file pointer, but may be useful for you, depending on how your code works.

 DIR *BaseDIR; struct dirent *curentDir; BaseDIR = opendir("path/to/the/directory"); while((curentDir = readdir(BaseDIR)) != NULL){ printf("directory or file name : %s\n",curentDir->d_name); } closedir(BaseDIR); 
-1
source

I think it's possible.
use fileno(fp) to get the handle.
Then you can use the fstat() function.

 The fstat() function shall obtain information about an open file asso‐ ciated with the file descriptor fildes, and shall write it to the area pointed to by buf. 

int fstat(int fildes, struct stat *buf);

then you can get a lot of information about files in *buf .

-2
source

Source: https://habr.com/ru/post/919097/


All Articles