我是一名来自 Rust 和 Golang 的 Zig 初学者。 我已经在网上搜索了几个小时,但只找到了不适合我的问题的极其复杂且低效的解决方案。
//Import standard library
const std = @import("std");
pub fn main() !void {
//Create an allocator
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
//Open desired file
var file = try std.fs.cwd().openFile("./state-of-union.txt", .{});
defer file.close();
//Regular buffer for demonstration purposes
var b = std.mem.zeroes([100]u8);
const x = try file.readAll(&b);
std.debug.print("Test bytes read: {any}\n", .{x});
//My *ACTUAL* buffer where the error arises
var buffer = std.ArrayList(u8).init(gpa.allocator());
defer buffer.deinit();
const temp = try file.readAll(buffer.items);
//Added to show that my code is not reading into my heap allocated array
std.debug.print("Actual bytes read: {any}\n", .{temp});
//Print file contents as string
std.debug.print("{s}\n", .{buffer.items});
}
输出:
~\Desktop\ztest via ↯ v0.12.0-dev.3152+90c1a2c41
❯ zig build run
Test bytes read: 100
Actual bytes read: 0
现在,如果我尝试将 buffer.items 更改为 &buffer.items 就像我对堆栈分配的缓冲区所做的那样,我会收到编译时错误:
~\Desktop\ztest via ↯ v0.12.0-dev.3152+90c1a2c41
❯ zig build run
run
└─ run ztest
└─ zig build-exe ztest Debug native 1 errors
src\main.zig:21:35: error: expected type '[]u8', found '*[]u8'
const temp = try file.readAll(&buffer.items);
^~~~~~~~~~~~~
C:\Program Files\zig\lib\std\fs\File.zig:1049:36: note: parameter type declared here
pub fn readAll(self: File, buffer: []u8) ReadError!usize {
^~~~
referenced by:
callMain: C:\Program Files\zig\lib\std\start.zig:511:32
WinStartup: C:\Program Files\zig\lib\std\start.zig:350:45
remaining reference traces hidden; use '-freference-trace' to see all reference traces
error: the following command failed with 1 compilation errors:
C:\Program Files\zig\zig.exe build-exe -ODebug -Mroot=C:\Users\user\Desktop\ztest\src\main.zig --cache-dir C:\Users\user\Desktop\ztest\zig-cache --global-cache-dir C:\Users\user\AppData\Lo
cal\zig --name ztest --listen=-
Build Summary: 2/7 steps succeeded; 1 failed (disable with --summary none)
run transitive failure
└─ run ztest transitive failure
├─ zig build-exe ztest Debug native 1 errors
└─ install transitive failure
└─ install ztest transitive failure
└─ zig build-exe ztest Debug native (reused)
error: the following build command failed with exit code 1:
C:\Users\user\Desktop\ztest\zig-cache\o\b91671406079ab60e0e46cf8f3eb5e2c\build.exe C:\Program Files\zig\zig.exe C:\Users\user\Desktop\ztest C:\Users\logan\Desktop\ztest\zig-cache C:\Users\user\AppData\Local\zig --seed 0xdd4267fc -Z3028407686deb58d run
主函数打开所需的文件,然后(演示后)声明一个堆分配的缓冲区并尝试从文件读取数据并写入缓冲区。然后打印缓冲区内容。
感谢任何帮助,我真的不知道出了什么问题。 (另外,如果有人可以将我链接到一些官方的 zig 示例,那将是真正令人难以置信的。我很难找到它们。)
您拨打
readAll
两次。 File.readAll
在底层调用 File.read
,目前尚未记录,但在查看 源代码 时,我们可以看到它是围绕 POSIX read
的薄包装 或(根据您的情况)Windows ReadFile
系统调用。
它们都有这样的行为:读取整个文件一次后,到达文件末尾,并且当尝试读取更多字节时,没有剩余字节可供读取。要将读取偏移重置为文件开头,您可以调用 。 这在 Rust 和 Go 中应该基本相同。