将二进制文件内容读入std :: string的最好方法是什么? [英] Which is the best way to read binary file content to std::string?
问题描述
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 to open the file。);
}
std :: stirng file_content;
//这里我需要好的方法来读取完整的文件到file_content
//注意:文件是二进制
ifile.close();
这是我知道的方法:
1.可能不安全
file_content.resize(ifile.tellg());
ifile.seekg(0,std :: ios :: beg); $!$ b 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); (ifile)
{
file_content + =(char)(ifile.get());
解决方案如果文件是二进制文件,它可能包含'\0'
,这是一个奇怪的字符被包含在 std :: string
中。虽然我认为你可以这样做,但是你会问一些问题,因为在 std :: string
上的一些操作需要一个 const char *
,它是空终止的。相反,使用 std :: vector< char>
,这是一个更安全的方法。
无论如何,只要调用 std :: string :: append(size_t,char)
。
contents.append(1,ifile.get());
$ b编辑:我认为你也可以做一些行: (std :: istreambuf_iterator< char>(ifile),std :: istreambuf_iterator< char>());
Possible Duplicate:
How to use istream with strings
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();
This are ways I know:
1.Maybe not safe
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.Slow
file_content.reserve(ifile.tellg());
ifile.seekg(0,std::ios::beg);
while(ifile)
{
file_content += (char)(ifile.get());
}
If the file is binary, it might contain '\0'
which is a weird character to be contained in an std::string
. Although I think you could do that, you will be asking for problems because some operations on a std::string
take a const char*
which is null-terminated. Instead, go with std::vector<char>
, a much safer way.
If you go with strings anyway, just do a loop calling std::string::append(size_t, char)
.
while(!ifile.eof()) {
contents.append(1, ifile.get());
}
EDIT: I think you can also do something in the lines of:
std::string contents(std::istreambuf_iterator<char>(ifile), std::istreambuf_iterator<char>());
这篇关于将二进制文件内容读入std :: string的最好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!