我有以下代码,最终永远读取'/ 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;
}
}
Run Code Online (Sandbox Code Playgroud)
for (int nRead = ::read(cpuFD, buf, bufSize); nRead != 0;) {
Run Code Online (Sandbox Code Playgroud)
是错的.您使用read作为初始化程序,因此只读取一次,而不是每次循环一次.在那之后,你只是循环永远打印出来(因为没有什么改变nRead).
| 归档时间: |
|
| 查看次数: |
717 次 |
| 最近记录: |