Sunday, March 20, 2005

Fast File Reading

There's a million ways to skin a cat or read a file but for my money this is the best



void FileToString(std::string filename, std::string& string)
{
    std::ifstream file;
    file.open(filename.c_str(), std::ios::binary | std::ios::ate);
    if (!file.is_open())
    {
        throw std::exception("Unable to read from file");
    }
 
    long lBufferSize = file.tellg();
    file.seekg(0, std::ios::beg);
 
    string.resize(lBufferSize +1);
 
    file.read(&string[0], lBufferSize);
    file.close();
}

No comments: