Writing File to User .cache Directory

I am making a simple helper application that changes the brightness of my screen, but I need to cache a value. How do I get the path for the user’s .cache directory so I can write a file there?

Getting the cache directory is platform specific.

XDG Base Directory Specification specifies:

$XDG_CACHE_HOME defines the base directory relative to which user-specific non-essential data files should be stored. If $XDG_CACHE_HOME is either not set or empty, a default equal to $HOME/.cache should be used.

Macos uses: ~/Library/Caches
Windows uses: %LOCALAPPDATA%\Temp

You can use the known-folders library to get the .cache folder or other well known folders.

2 Likes

Thank you. I was messing with std.fs.realpath and felt like something was wrong lol.

1 Like

Here’s what I use to get a path to a subdir within the cache directory FWIW:

(it’s basically the same as what @dimdin describes and what known-folders does)

4 Likes

known-folders is probably a better solution, but if you only need the cache directory, you can just yank this function from the compiler.

2 Likes

Note that this code is for getting the zig cache directory.

1 Like

I’m a bit confused about the preferred path to cache on Windows.

Both the Go std and Zig compiler use %LocalAppData%, but resinator and known-folders use %LocalAppData%/Temp.

This usage is not documented in Environment variable - Wikipedia and, personally, the last path should be Cache, instead of Temp.