Given a file pointer fp which points to an open file, is there a portable way to give it a name? The function rename cannot be used in this case since I don't have a current name referring to the file.
Asked
Active
Viewed 452 times
-1
-
"_points to an open file_"...what does that mean? – machine_1 Sep 19 '16 at 15:24
-
1Possible duplicate of [Relinking an anonymous (unlinked but open) file](http://stackoverflow.com/questions/4171713/relinking-an-anonymous-unlinked-but-open-file) – slim Sep 19 '16 at 15:26
-
1I think the "possible dupe" mostly answers your question -- you can't. The only possible difference is that your file might be linked to a filename somewhere, but it's still a security "thing" that you're not allowed to discover that relationship backwards. – slim Sep 19 '16 at 15:28
-
@machine_1 I mean a FILE pointer which is not NULL (and not undefined). – August Karlstrom Sep 19 '16 at 15:33
-
Correction - the "possible dupe" does refer to `linkat` and `AT_EMPTY_PATH` which works on Linux since 2.6.39 (but probably isn't portable). – slim Sep 19 '16 at 15:34
1 Answers
3
On linux, you can use linkat
int linkat(int olddirfd, const char *oldpath,
int newdirfd, const char *newpath, int flags);
by specifying the AT_EMPTY_PATH
flag. For example, something like that:
linkat(fileno(fp), NULL, AT_FDCWD, "/path/to/new/name", AT_EMPTY_PATH);
Note that this does not rename the original file, it merely creates a new hard link to it (i.e. a new name). Also this approach is not portable, as the AT_EMPTY_PATH
is a linux extension.

redneb
- 21,794
- 6
- 42
- 54
-
`fp` should be `fileno(fp)`, since he mentioned that `fp` is a `FILE*`. – Barmar Sep 19 '16 at 15:39
-
This answer is confusing because the example call to `linkat` you wrote doesn't use the described `AT_EMPTY_PATH`. – Ian Abbott Sep 19 '16 at 15:44
-
-
`linkat` is not just Linux. It's also [POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/functions/link.html). The [Linux man page](http://man7.org/linux/man-pages/man2/link.2.html) also has an interesting solution: "If procfs is mounted, this can be used as an alternative to AT_EMPTY_PATH, like this: `linkat(AT_FDCWD, "/proc/self/fd/
", newdirfd, newname, AT_SYMLINK_FOLLOW);`" That may work on non-Linux Unix systems with a `/proc` filesystem, also. – Andrew Henle Sep 19 '16 at 15:51 -
-
@redneb True, but you'd already mentioned that. I was just adding that `linkat` is POSIX and the relink method mentioned in the Linux man page may work on other Unix systems. – Andrew Henle Sep 19 '16 at 15:56