Determining the (open) file name from the FILE * file

Given the stdio FILE * pointer, is there a way I can find out the name of a (open) file?

+3
source share
3 answers

It seems (from here ) that on POSIX systems, you can use fileno () to get the file descriptor from FILE *, then use fstat to get status information from the file descriptor. The stat structure contains the device number and inode number. You can check the file system for files matching the index. This will obviously take some time for a file system full of material.

The reason this is not possible (as explained in a related article) is because the stream may not have a file name if it is something like stdin or stdout, or if it is an open file that has been deleted. It may also have multiple names due to hardlinks.

A related article mentions this comp.lang.c FAQ , which briefly describes the unsolvability of this problem.

EDIT: Thanks for the fix.

+8
source

No no. Among other things, FILE * may not refer to a named file. If your application needs this tool, you need to save some kind of card from the open FILE * s to the file name that you used to open them.

+2
source

There is no standard portable solution. However, you can take a look at the set of OSs you installed. POSIX systems have a fstat function that takes a descriptor (not FILE * ) and returns some information.

+1
source

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


All Articles