我试图解析/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