如何使用低级系统调用从 stdin 和输入文件中获取字节数

How to get number of bytes from stdin and input file using low level system calls

本文关键字:文件 输入 获取 字节数 stdin 何使用 系统调用      更新时间:2023-10-16

如何使用低级系统调用从 stdin 和输入文件中获取字节数? 如 read(2) 和 write(2)

我使用 lseek 从输入文件中获取字节数,但 lseek 不适用于标准输入。

我想尝试逐字节读取文件或标准输入字节,并将它们存储到数组中并打印出文件或标准输入中的总字节数。我尝试使用 for 循环来做到这一点。 就像标准输入一样...

while((x = read(0, bf, bsize)) > 0) //reading the standard input
{
for(int i = 0; i < n; i++)
{
//try to implement getting the total amount of bytes that are in STDIN here
}
}

这就是我试图做的,但我认为我使用 for 循环做错了。

我真的不知道如何实现获取标准输入和输入文件中的字节数。有人可以帮我吗?

您无法从stdin/std::cin获取字节数,因为您无法转到这些流中的特定位置。此外,您无法倒带它们。

最好的选择是在读取字节时将字节存储在std::vector中。

std::vector<char> arr;
int c;
while ( (c = std::cin.get()) != EOF )
{
arr.push_back(c);
}
size_t size = arr.size();