Get absolute path of zig project

I have a zig project which might look like this:

.
├── build.zig
├── src
│   └── main.zig
└── testdata
    └── data.txt

Now in src/main.zig I have a unit test that depends on data.txt and needs its absolute path. Right now I have hard coded the absolute path to data.txt in the unit test. What is an idiomatic way to obtain the absolute path?

Can’t you just open "../testdata/data.txt"?

2 Likes

If I do that I would have to pass the path relative to std.fs.cwd(), which is the directory where the executable is invoked from. Do I understand that correctly? I would prefer to pass a path relative to the source code directory.

The reason why a relative path is a better choice IMHO is that if you move your project to a different location then your tests would fail until they are recompiled (which, granted, is not a big issue since zig build test might take care of it automatically, but you can run them from zig-cache or store them in a custom binary with -femit-bin=...).

If you’re hell-bent on using an absolute path, you can use something like std.fs.cwd().realpath("testdata/data.txt") in your build.zig.

1 Like

I’m not sure why you need the absolute path. Could you explain more why you need an absolute path? Maybe “@embedFile” could be of use to you here?

1 Like

I’m not sure why you need the absolute path. Could you explain more why you need an absolute path? Maybe “@embedFile” could be of use to you here?

The main inconvenience is that now with relative path zig build test only works if I invoke it from the project base directory. If I invoke it from another directory things fail. But it is not the end of the world and probably my best option.

Thanks @jmc for explaining the options. I will go with relative path.