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
source share