Re: Saving a binary file into a string
On Sun, 27 Dec 2009 13:06:03 -0800 (PST), Jonathan Lee wrote:
But still, it just seems odd. If you follow Rune's advice
and use a std::vector, just resize it to the file size
and read directly into the vector:
I'm just anal about types. tellg() returns a streampos,
which is defined by the standard to be a signed integral
type. So it will fit into long long; you won't have a
problem with that.
Thank you all for your many tips.
Here is my code (the new part). Error handling is still missing.
std::streampos GetFileSize(string FilePath)
{
std::streampos Out1 = -1;
ifstream file1;
file1.open (FilePath.c_str(), ios::binary);
if (file1.is_open())
{
file1.seekg(0, ios::end);
Out1 = file1.tellg();
}
file1.close();
return Out1;
}
std::vector<char> OpenFile(string FilePath)
{
std::vector<char> Out1;
ifstream file1;
std::streampos filesize;
filesize = GetFileSize(FilePath);
file1.open (FilePath.c_str(), ios::binary);
if (file1.is_open())
{
Out1.resize(filesize);
file1.read(&Out1[0], filesize);
}
file1.close ();
return Out1;
}
void SaveFile(string FilePath, std::vector<char> FileContent)
{
ofstream file1;
std::streampos filesize;
filesize = FileContent.size();
if (FileExists(FilePath)) KillFile(FilePath);
if (FileExists(FilePath)) return;
file1.open (FilePath.c_str(), ios::binary);
if (file1.is_open())
{
file1.write(&FileContent[0], filesize);
}
file1.close();
}