3

In C on linux, given a file path, I'd like to read the file contents, and also I'd like to know the real path with any symlinks resolved. I can do those things separately (e.g. open() + read() for the former, realpath() for the latter), but it feels there's some redundant work happening, because doesn't open() already have to follow all the symlinks internally? Is there a way to somehow access that result and get both the file descriptor and the real path in one operation, instead of having realpath() do the resolution a second time?

Intuitively it feels like it might be faster to do the realpath() first and then pass the resolved path to open(), but I guess open() will still have to check whether any of the path components are symlinks even though I know they aren't.

9
  • How small does this redundant work have to be for you to not care? Commented Aug 8 at 15:27
  • I feel like it might add up if I'm dealing with a lot of files 🙂 Commented Aug 8 at 15:29
  • But what if that sum is still under your threshold for caring? Commented Aug 8 at 15:31
  • 4
    Note that you can also run into a TOCTOU issue. Symlinks can be changed after you open the file, so the real path may not match what was originally used. Commented Aug 8 at 15:54
  • 6
    This sounds like it may be an XY problem. What problem are you trying to solve by getting the real path of a file you opened? Commented Aug 8 at 15:55

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.