Getting the length of the stdin buffer on Linux

Hello everyone,

i am new to zig and as a learning project i decided to work on my own posix utilities.

Currently working on cat and i am using the following code to write the stdin content to stdout:

    const stdin = std.Io.File.stdin();
    const stdin_size = try stdin.length(io);
    const buf: []u8 = try allocator.alloc(u8, stdin_size);
    defer allocator.free(buf);
    var reader = stdin.reader(io, buf);
    _ = try reader.interface.readSliceAll(buf);
    
    try std.Io.File.stdout().writeStreamingAll(io, buf);

On my OpenBSD machine this works like a charm, but on Linux stdin.length always returns 0, even when i am piping data into my program.

Is there a cross platform way of getting the length of stdin, so that i know how much memory i have to allocate?

(i am using zig 0.17.0)

I’ll hazard a guess that the answer is mostly no, or at least not consistently. e.g. on Linux unless you know stdin happens to be a file it won’t work. For a pipe, terminal, etc. you’ll get the 0 you’re seeing here until you read the whole stream.

Can you make that assumption?