fstream 示例代码

fstream 示例代码

参考:C++中文件流(fstream)的使用方法及示例

  1. 获取流长度,并读取。
int _tmain(int argc, _TCHAR* argv[])
{
    using namespace std;
    ifstream stream("F:\\WorkSpace\\StreamDemo\\Debug\\abc.txt", ios::in);
    if(!stream)
        cerr << "Open failed" << endl;
    stream.seekg(0, ios::end);
    int len = stream.tellg();
    stream.seekg(0, ios::beg);
    char* buffer = new char[len];
    memset(buffer, '\0', len);
    if(!stream.read(buffer, len))
    {
        cout << "Read error:" << stream.rdstate() << endl;
    }
    cout.write(buffer, len);
    stream.close();
    system("pause");
    return 0;
}
  1. mysql 读取blob。
std::stringstream s;
        s << "SELECT * FROM Dao WHERE gender = "<< data <<"";

        prepStmt = con->prepareStatement (s.str());
        res = prepStmt->executeQuery();

        unsigned char* ptr;
        size_t blobSize=100;
        std::istream *is;
        while(res->next()){
            tempFR.uuId = res->getInt64("uuId");
            tempFR.cameraNo = res->getInt("cameraNo");
            tempFR.age = res->getInt("age");
            tempFR.gender = res->getInt("gender");
            is = res->getBlob("image");
            is->seekg (0, std::ios::end);
            blobSize = is->tellg();
            is->seekg (0, std::ios::beg);
            unsigned char * image = new unsigned char[blobSize];
            is->read((char*)image, blobSize);
            size_t imageSize = blobSize;
        }
  • 另外一种没用过:
std::istream *blobData = set->getBlob("image");
std::istreambuf_iterator<char> isb = std::istreambuf_iterator<char>(*blobData);
std::string blobString = std::string(isb, std::istreambuf_iterator<char>());
unsigned char * image = blobString.c_str();
blobData->seekg(0, ios::end);
size_t imageSize = blobData->tellg();

你可能感兴趣的:(C++)