gpt4 book ai didi

c++ - 为什么 read of/proc/cpuinfo 似乎没有提升文件位置?

转载 作者:行者123 更新时间:2023-11-27 22:31:56 25 4
gpt4 key购买 nike

我有以下代码,它最终会永远读取“/proc/cpuinfo”,因为它每次读取都会得到相同的结果。为什么文件指针永远不会前进并到达eof?似乎这个特殊文件有不同的语义。

  const int bufSize = 4096;
char buf[bufSize + 1];
const string cpuInfo = "/proc/cpuinfo";
int cpuFD = ::open(cpuInfo.c_str(), O_RDONLY);

if (cpuFD == -1) {
logOutputStream << "Failed attempt to open '" << cpuInfo << "': "
<< strerror(errno) << endl;
} else {
assert(bufSize <= SSIZE_MAX);

logOutputStream << "Contents of: '" << cpuInfo << "'.\n";

for (int nRead = ::read(cpuFD, buf, bufSize); nRead != 0;) {
if (nRead == -1) {
logOutputStream << "Failed attempt to read '" << cpuInfo << "': "
<< strerror(errno) << endl;
break;
} else {
buf[nRead] = '\0';
logOutputStream << buf;
}
}
if (::close(cpuFD) == -1) {
logOutputStream << "Failed attempt to close '" << cpuInfo << "': "
<< strerror(errno) << endl;
}
}

最佳答案

for (int nRead = ::read(cpuFD, buf, bufSize); nRead != 0;) {

错了。您将 read 用作初始值设定项,因此 read 仅被调用一次,不是每个循环调用一次。之后,您将永远循环打印它(因为 nRead 没有任何变化)。

关于c++ - 为什么 read of/proc/cpuinfo 似乎没有提升文件位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1391641/

25 4 0
文章推荐: css - 在另一个