Skip to content

Instantly share code, notes, and snippets.

@CMCDragonkai
Last active October 11, 2018 04:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CMCDragonkai/cba1a74e3eaedfcb92b88527f759fa36 to your computer and use it in GitHub Desktop.
Save CMCDragonkai/cba1a74e3eaedfcb92b88527f759fa36 to your computer and use it in GitHub Desktop.
Using File Descriptors for Temporary Files and Temporary Directories

Using File Descriptors for Temporary Files and Temporary Directories

You can easily use file descriptors to create temporary files:

tmpfile=$(mktemp /tmp/abc-script.XXXXXX)
exec 3<>"$tmpfile"
echo 'Hello World' >"$tmpfile"
rm "$tmpfile"
cat <&3

In Python you can just use with tempfile.TemporaryFile(). It also does the same thing on supported operating systems.

What about directories? Can we get a "virtual" directory?

Well there are these things called directory descriptors.

It seems that it should be possible to create a directory, opening a directory descriptor, and then unlinking the directory path.

Then using the functions openat or *at functions to work on that descriptor.

However trying it to do this via Python's os.* functions that has the dir_fd parameter doesn't work. You can delete the directory, and but when using those functions, you end up with errors about FileNotFound. However the normal os.f* functions does work on the directory descriptor when the directory is deleted.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment