I want to create a totally new IO object which refers to the file pointed by the old FILE *
You're assuming that the file associated with the original FILE *
has some form of identity distinct from the IO object by which it is accessed. That is true for regular files and some other objects, but false for others, such as sockets and pipes. Thus, there is no general-purpose mechanism for doing what you ask.
For the special case of objects that can be accessed via the file system, the way to create a new IO object associated with the same file is to open()
or fopen()
the file via a path to it. That's what these functions do. There is no standard way to get a path from a FILE *
or file descriptor number, but on Linux (since you tagged that) you can use readlink()
on the open file's entry in /proc
, as described here.
Do be aware that even for regular files, the readlink
approach is not guaranteed to work. In particular, it will not work if the path with which the original file was opened has since been unlinked, and in fact, in that case it could lead to the wrong file being opened instead. You can check for that by running fstat()
on both the old and new file descriptor numbers -- if the files are in fact the same, then they will have the same inode numbers on the same host device.