1.我正在尝试逐行读取文件,但它不会。我以前一步一步地阅读整个文件没有问题。我将接收数据的矢量更改为本地矢量作为实验(没有成功)。我怀疑我做的事情显然是错的,除了我。
int
full_file_read( std::vector<std::string> &data ,
const std::string& filename ,
bool is_binary )
{
std::string line ;
std::ios_base::openmode openmode = std::ios::ate | std::ios::in ;
if ( is_binary )
{
openmode |= std::ios::binary ;
}
std::fstream file( filename , openmode ) ;
if ( !file )
{
std::cerr << "Can't open input file! "
<< filename << std::endl ;
}
std::vector<std::string> text ;
// to verify that it likes the push back for data is not the problem
if ( file.is_open() )
{
while ( std::getline( file , line ) )
{
text.push_back( line ) ;
// data.push_back( line ) ;
}
}
else
{
std::cerr << "Opening of " << filename
<< " failed!" << std::endl ;
}
std::cout << "file contents: " << std::endl ;
for ( auto const& c : line )
{
std::cout << c << ' ' << std::endl ;
}
return 0 ;
}
2.在不使用调试的情况下运行时,我得到一个seg-fault。在gdb中,while循环不执行。数据文件如下
i have a comment here
and another over there
yet another in somewhere unknown
for reasons only (dr) who noses
NumParticles|SimWidth|SimHeight|ViewWidth|ViewHeight|Softener|Zoom|MouseX|MouseY|MassMin|MassMax|CenterMass|DiskMin|DiskMax
10000000,327680,327680,1366,768,10,1,0,0,1,2,100000,2000000,5
TIA
答案 0 :(得分:1)
std::ios::ate
表示在文件的 end 处打开。您通常只有在您写入文件时才使用此功能,而您在阅读时并不想使用它。通过将其包含在此处,您可以在第一个getline
上获得文件结尾。
我无法解释段错误,这通常是由未定义的行为引起的。也许它在此函数返回后的代码中。