2009-09-08 97 views
0

我有以下代码永远读取'/ proc/cpuinfo',因为它每次读取都会得到相同的结果。为什么文件指针没有进入高级并达到有效期?看起来这个特殊文件有不同的语义。为什么读取/ proc/cpuinfo似乎不提前文件位置?

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; 
    } 
    } 

回答

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

是错误的。您正在使用读取作为初始化程序,因此只读取一次,而不是每个循环一次。之后,你只是循环打印出来(因为没有改变nRead)。

+0

感谢您检测到这个脑屁! – WilliamKF 2009-09-09 16:00:05

0

,如果你尝试倾倒内容为实际的文本文件,像

cat /proc/cpuinfo > cpuinfo.txt 

,然后读取该文件,会发生什么?

相关问题