我試圖解析/proc/partitions
文件。流>>最後一行讀兩次
major minor #blocks name
8 0 976762584 sda
8 1 99998720 sda1
8 2 1 sda2
8 3 103561216 sda3
8 4 291514368 sda4
8 5 1998848 sda5
這是我機器中的/ proc /分區文件。
#include <boost/cstdint.hpp>
#include <fstream>
#include <boost/algorithm/string/trim.hpp>
#include <boost/format.hpp>
int main(){
std::ifstream proc_partitions_stream("/proc/partitions");
boost::int32_t disc_partition_line_count = -2; //-1 for headers, -1 for the empty line
//so counter is 0 when it tries to read the real entries
while(!proc_partitions_stream.fail()){
if(disc_partition_line_count >= 0){
boost::uint16_t major, minor;
boost::uint64_t blocks;
std::string label;
proc_partitions_stream >> major >> minor >> blocks >> label;
std::cout << boost::format("%1% %2% %3% %4%") % major % minor % blocks % label << std::endl;
boost::algorithm::trim(label);
}else{
std::string line;
std::getline(proc_partitions_stream, line);
}
++disc_partition_line_count;
}
return 0;
}
但它讀取最後一行兩次這裏是程序
8 0 976762584 [sda]
8 1 99998720 [sda1]
8 2 1 [sda2]
8 3 103561216 [sda3]
8 4 291514368 [sda4]
8 5 1998848 [sda5]
8 5 1998848 [] << read the last line TWICE but didn't read the label
你永遠不會檢查你的輸入提取成功。而你的循環並不比在while-conditional中檢查eof更好[[這幾乎是*總是*錯]](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-循環條件被認爲是錯誤的) – WhozCraig