Is it possible to retrieve a file's name in C? If a file is created like the following:
FILE *f = fopen ("foo.txt", "r");
And the "foo.txt" comes from a variable out of scope. Is there a way to retrieve it from the FILE struct?
You can't in fact retrieve the file names from your FILE
objects.
However, if the name being passed to fopen
is important to you, and that variable is out of scope for whatever reason, you could always wrap a FILE*
in a struct, ie.
struct file_with_name {
FILE *f;
char *name; /* OR char name[MAX] */
}
At least that's what I'd do but it depends on what you're actually trying to do.
Unfortunately, on many systems a filename is just a pointer to an inode. And if those filesystems support hard links, that means that there are multiple filenames per real file. Also, you can open a file and then remove the file in which case there wouldn't even be a filename, just a descriptor. For these reasons, you can't go from a file descriptor to a file name.
Its not possible to get the filename out of a FILE
handle. You should store the filename yourself if you later need to use it.
Since FILE
objects may be created from things that have no name associated with them (in particular, from a raw file descriptor with fdopen()
), they do not always have a name to get.
In general, it's not possible. The closest you can try, on Linux, is:
char buf[PATH_MAX];
snprintf(buf, sizeof buf, "/proc/self/fd/%d", fileno(f));
readlink(buf, buf, sizeof buf);
Reusing buf
like that is horribly ugly, but as far as I can tell, it's legal and not undefined behavior per POSIX.