【发布时间】:2011-06-30 08:44:46
【问题描述】:
std::ifstream ifile(absolute_file_path.c_str(),std::ios::binary | std::ios::in | std::ios::ate);
if (ifile.is_open()==false)
{
throw std::runtime_error("Unable open the file.");
}
std::stirng file_content;
//here I need good way to read full file to file_content
//note: the file is binary
ifile.close();
这是我知道的方式:
1.可能不安全
file_content.resize(ifile.tellg());
ifile.seekg(0,std::ios::beg);
if(!ifile.read(const_cast<char *>(file_content.data()), file_content.size()));
{
throw std::runtime_errro("failed to read file:");
}
ifile.close();
2.慢
file_content.reserve(ifile.tellg());
ifile.seekg(0,std::ios::beg);
while(ifile)
{
file_content += (char)(ifile.get());
}
【问题讨论】:
-
您可能会发现另一个问题的答案很有用:stackoverflow.com/questions/5632572/…
-
字符串不是为保存二进制数据而设计的,您应该使用类似向量的东西
-
您最好使用
while (ifile)而不是while (!ifile.eof())(这可能会变成无限循环)。 -
查看这个问题以了解读取二进制文件的正确方法:stackoverflow.com/q/4761529/11343
-
@Mihran: Looping with
!stream.eof()is wrong.