C++ code snip

阅读更多

1. 将文件内容读取为string

   a.

 

string readFile2(const string &fileName)
{
    ifstream ifs(fileName.c_str(), ios::in | ios::binary | ios::ate);

    ifstream::pos_type fileSize = ifs.tellg();
    ifs.seekg(0, ios::beg);

    vector bytes(fileSize);
    ifs.read(&bytes[0], fileSize);

    return string(&bytes[0], fileSize);
}

 b.

#include 
#include 

void slurp(const std::string& filename, std::string& data, bool is_binary)
{
        std::ios_base::openmode openmode = std::ios::ate | std::ios::in;
        if (is_binary)
                openmode |= std::ios::binary;

        std::ifstream file(filename.c_str(), openmode);
        if (!file.is_open())
        {
                throw "error opening file";
        }

        data.clear();
        data.reserve(file.tellg()); // alocate all memory in one go

        file.seekg(0, std::ios::beg);

        char buf[1000];
        while ( file )
        {
                file.read(buf, 1000);
                data.append(buf, file.gcount());
        }

        if ( file.bad() )
        {
                // an error occurred while reading
                throw "error while reading file";
        }
}

 

你可能感兴趣的:(C,C++,C#,iOS,Go)