AFAIK, there's no system-independent way to do this.
In Linux, it's possible to coerce the information from the /proc
filesystem (see below).
Other systems may have some other way to get at this information.

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>

char *get_filename(int fd)
{
  static char buf[1024];
  char path[128];
  sprintf(path, "/proc/%d/fd/%d", getpid(), fd);
  if (readlink(path, buf, sizeof(buf)) == -1)
    strcpy(buf, "readlink error");
  return buf;
}

int main(int argc, char **argv)
{
  FILE *fp = fopen("/etc/passwd", "r");
  if (fp)
  {
    printf("File: %s\n", get_filename(fileno(fp)));
    fclose(fp);
  }
}

Reply via email to