[LCP]getting the filename from a *FILE variable
Steve Baker
ice at mama.indstate.edu
Wed Jan 12 22:48:02 UTC 2005
Karthik Vishwanath <karthikv at Alum.Dartmouth.ORG> wrote:
> I have files parsed from the command line in a program that are
> opened using (fp = fopen()), where fp is defined as FILE *fp;
>
> Is there a function that will give me the filename of the fopen'd file
> using fp?
First, as Greg noted, you should probably just keep track of the name
yourself, but if for some reason that is impossible, you can learn what the
filename is via the proc filesystem. This can be useful if you'd like to know
what the filenames are for redirected stdin/stdout/stderr.
FILE *fp;
char pf[256], file[1025];
int fd, n;
/* Get the file descriptor # for the stream */
fd = fileno(fp);
/* use that to get the path into /proc. */
sprintf(pf,"/proc/self/fd/%d",fd);
/* Read the link the file descriptor points to in the /proc filesystem */
n = readlink(pf,file,1024);
file[n] = 0;
/* Print the result. */
printf("%s\n",file);
Note that readlink() may fail if your buffer is not of sufficent size, check
the error codes. Also note that you will get the full path to the filename,
not just it's name from the readlink().
- Steve
More information about the linuxCprogramming
mailing list