Using LIBMONGOC, refer to: http://mongoc.org/libmongoc/current/mongoc_gridfs_t.html
#include <mongoc.h>#include<stdio.h>#include<stdlib.h>#include<fcntl.h>classMongogridfs { Public: Mongogridfs (Const Char*db); ~Mongogridfs (); voidSaveFile (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);}voidMongogridfs::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 ();}intMain (intargcChar*argv[]) {Mongogridfs Gridfs ("Test2gridfs"); Gridfs.savefile ("test.py","test.py"); return 0;}
MongoDB C + + Gridfs worked example