开发者

Which is the best way to read binary file content to std::string? [duplicate]

开发者 https://www.devze.com 2023-03-16 04:44 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: How to use istream with strings
This question already has answers here: Closed 11 years ago.

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(ifi开发者_运维知识库le.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>());


You should be clear with binary file and string. Do you mean to read the content of that file, or you want to read binary representation of the file to string? Normally an unsigned char[] buffer is used to store content of binary files. And string is used to store content of a text file.

0

精彩评论

暂无评论...
验证码 换一张
取 消