I’m learning the Io interface and be trying to find some C function equivalents, for example, the getcwd(3) C function, to make a tiny program behaves like the pwd(1) utility. I tried two approaches, first std.c.getcwd(), and std.process.currentPath() secondly:
In general, file operations in Zig operate relative to a target directory, and std.Io.Dir.cwd() gets you the working directory. Most of the operations you’d do on paths in a lot of other languages operate on Io.Dir or Io.Files exclusively in Zig.
I learned lots of new stuffs here: 1) how to convert a many-item pointer to a slice 2) use process.currentPath as the end: usize 3) use FixBufferallocator API instead of buffer 4) Io.Dir.cwd is where operations on File/Dir we usually need. You guys are true talents.
Oh, sorry, my example using fixedBufferAllocator might have been a bit misleading. I only used it to make currentPathAlloc behave as similarly to currentPath as possible. Generally, if we want to use currentPathAlloc, we can just manage it with a regular heap allocator. If you want to manage it on the stack, you usually use currentPath without going around.
Although many people prefer to avoid using the heap, I think managing it on the heap is appropriate here, because essentially, from a cross-platform perspective, there isn’t really a maximum path length. std.c.MAX_PATH isn’t a true limit; it’s just a commonly enforced buffer size limit and isn’t really usable across platforms.
std.process.currentPath or std.process.currentPathAlloc.
The currently accepted answer of using std.c.getcwd introduces an unnecessary dependency on libc and bypasses the std.Io interface which is okay to do in an application where you control everything, but in a reusable package meant to be consumed by third parties is entirely unacceptable.