使用 windows.h 读取 c 中的行

发布于 2024-10-21 07:20:39 字数 202 浏览 4 评论 0原文

我需要使用 windows.h 的系统调用来读取从命令行获取的文件。我可以使用 ReadFile() 读取整个文件以进行缓冲区,然后在第一个 \0 处剪切缓冲区,但如何只读取一行?另外我需要读取文件的最后一行,这是否可以在不将整个文件读入缓冲区的情况下实现,因为文件可能是 4GB 或更大,所以我将无法读取它。那么有人知道如何逐行阅读吗?

I need to use system-calls of windows.h to read a file which I get from command line. I can read to whole file to buffer using ReadFile() and then cut the buffer at the first \0, but how can I read only one line? Also I need to read the last line of the file, Is this possible without reading the whole file into buffer, because maybe the file is 4gb or more so I won't be able to read it. So anyone knows how to read it by lines?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

╄→承喏 2024-10-28 07:20:39

如果您知道排队的长度,那么您就可以做一个比最大排队稍大的缓冲区。

ReadFile 读取多个字节并在行的第一个末尾剪切缓冲区 (\n)

使用 LZSeek 定位到文件末尾,然后向后移动一行字节并查找行尾,从那里开始并读取行的其余部分。

If you have an idea of how long lines are then you are in business, make a buffer that is a bit larger than max line.

ReadFile read a number of bytes and cut buffer at first end of line (\n)

Use LZSeek to position at end of file, then move back a line of bytes and look for end of line, start there and read rest of line.

真心难拥有 2024-10-28 07:20:39

不要“在第一个 \0 处剪切缓冲区”,ReadFile 不会返回以零结尾的字符串。它读取原始字节。您必须注意通过 lpNumberOfBytesRead 参数返回的值。除非到达文件末尾,否则它将等于您传递的 nNumberOfBytesToRead 值。

现在您知道缓冲区中有多少有效字节。在它们中搜索第一个“\r”或“\n”字节以查找行终止符。将字节范围复制到调用者提供的字符串缓冲区并返回。下次阅读一行时,从上次停下的地方开始,越过行终止符。当您找不到行终止符时,您必须复制缓冲区中的字节并再次调用 ReadFile() 以读取更多字节。这使得代码有点难以正确编写,否则是很好的练习。

Don't "cut the buffer at the first \0", ReadFile doesn't return a zero-terminated string. It reads raw bytes. You have to pay attention to the value returned through the lpNumberOfBytesRead argument. It will be equal to the nNumberOfBytesToRead value you pass unless you've reached the end of the file.

Now you know how many valid bytes are in the buffer. Search them for the first '\r' or '\n' byte to find the line terminator. Copy the range of bytes to a string buffer supplied by the caller and return. The next time you read a line, start where you left off previously, past the line terminator. When you don't find the line terminator then you have to copy the bytes in the buffer and call ReadFile() again to read more bytes. That makes the code a bit tricky to get right, excellent exercise otherwise.

情感失落者 2024-10-28 07:20:39

对于您想要做的事情来说,ReadFile 是一个特别糟糕的选择。您是否可以使用 fgets?在您的情况下,这会更容易使用。

ReadFile is a particularly poor choice for what you want to do. Are you allowed to use fgets? That would be much easier to use in your case.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文