MongoDB C++ gridfs worked example

使用libmongoc,参考:http://mongoc.org/libmongoc/current/mongoc_gridfs_t.html

#include <mongoc.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>


class MongoGridFS {
public:
    MongoGridFS(const char* db);
    ~MongoGridFS();

    void saveFile(const char* input_file_path, const char* filename);
private:
    mongoc_gridfs_t *gridfs;
    mongoc_client_t *client;
};


MongoGridFS::MongoGridFS(const char* db) {
    assert(db != NULL);
    mongoc_init ();
    /* connect to localhost client */
    client = mongoc_client_new ("mongodb://127.0.0.1:27017?appname=gridfs-example");
    assert (client);
    mongoc_client_set_error_api (client, 2);

    /* grab a gridfs handle in test prefixed by fs */
    bson_error_t error;
    gridfs = mongoc_client_get_gridfs (client, db, "fs", &error);
    assert (gridfs);
}


void MongoGridFS::saveFile(const char* input_file_path, const char* filename) {
    assert(input_file_path != NULL && filename != NULL);
    mongoc_stream_t *stream = mongoc_stream_file_new_for_path (input_file_path, O_RDONLY, 0);
    assert (stream);

    mongoc_gridfs_file_opt_t opt = {0};
    opt.filename = filename;

    /* the driver generates a file_id for you */
    mongoc_gridfs_file_t *file = mongoc_gridfs_create_file_from_stream (gridfs, stream, &opt);
    assert (file);

    mongoc_gridfs_file_save (file);
    mongoc_gridfs_file_destroy (file);
}


MongoGridFS::~MongoGridFS() {
     mongoc_gridfs_destroy (gridfs);
     mongoc_client_destroy (client);
     mongoc_cleanup ();
}


int
main (int argc, char *argv[])
{
    MongoGridFS gridfs("test2gridfs");
    gridfs.saveFile("test.py", "test.py");
    return 0;
}

原文链接: https://www.cnblogs.com/bonelee/p/6568211.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/251012

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月14日 上午4:56
下一篇 2023年2月14日 上午4:59

相关推荐