Why there is no `stat` function in Zig

I noted that std.os only have the fstat function, but not stat.

stat function is only available when linking libc.
What is the reason?

Also, looking at the code in std.c, it seems that fstat is not available in macos and netbsd, but looking on internet they are supported.

Thanks.

1 Like

The Zig std.fs API is largely based around using file descriptors rather than paths when possible, so std.os.stat doesn’t exist because there’s nothing in the standard library that depends on it.

Instead, you’d do something like:

// If you have an open File:
const stat = try file.stat();

// If you have an open Dir:
const stat = try dir.stat();

// If you have an open Dir and want to stat a child path:
const stat = try dir.statFile("some_file");

// If you have no open File/Dir, you can use std.fs.cwd()
// (this will work for both relative and absolute paths):
const stat = try std.fs.cwd().statFile(some_path);

Note that the Dir.statFile examples will currently behave differently per-platform (it will error on Windows if the path refers to a directory). This is a known flaw that will be resolved by `std.fs` is missing an "open any" API · Issue #16738 · ziglang/zig · GitHub.

See also Remove `fooAbsolute` functions from `std.fs` · Issue #16736 · ziglang/zig · GitHub for some more information about the Dir-based API design (the proposal was closed without being accepted, but the information within it is relevant).

3 Likes

Thanks.

In a program I had to use the stat syscall, and the first thing I did was to search in the os namespace. Later I searched in fs.File and I did the crazy thing to:

var file = try fs.cwd.openFile(file_path, .{});
defer file.close();

const stat = try file.stat();

Only later I noted Dir.statFile

I have played with Zig for about 2 years, but I still have to get used to the fs API.