2009-09-08 73 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 

,然後讀取該文件,會發生什麼?

相關問題