我有以下代码,最终会永远读取'/ 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;
}
}
答案 0 :(得分:5)
for (int nRead = ::read(cpuFD, buf, bufSize); nRead != 0;) {
错了。您使用read作为初始化程序,因此只读一次,不每次循环一次。在那之后,你只是循环永远打印出来(因为没有什么改变nRead)。
答案 1 :(得分:0)
如果尝试将内容转储到类似
的实际文本文件中会发生什么cat /proc/cpuinfo > cpuinfo.txt
然后读取该文件?