Wednesday, November 4, 2009

read write file from gridfs

This simple program reads file from gridfs and write its content to local file system.

//gridfs_to_file.cpp
#include <iostream>
#include <vector>
#include <fstream>

#include <boost/algorithm/string.hpp>

#include <mongo/client/dbclient.h>
#include <mongo/client/gridfs.h>

// g++ gridfs_to_file.cpp -lmongoclient -lboost_thread -lboost_filesystem -o gridfs_to_file

using namespace std;
using namespace mongo;

int main(int argc, const char **argv) {
   const char *gridFileName = "";
   std::fstream out;


   if (argc != 3) {
      cerr << "Usage " << argv[0] << " gridfs_file local_file"  << endl;
      return -12;
   }

   out.open(argv[2], ios::out);

   if ( !out.is_open()) {
      cerr << "Can't open " << argv[2] << endl;
      return -2;
   }
   gridFileName = argv[1];

   DBClientConnection c;
   c.connect("localhost"); 
   cout << "connected ok" <<endl;
   GridFS gfs = GridFS(c, "test", "testcpp");
   GridFile gf = gfs.findFile(gridFileName);

   if (true != gf.exists()) {
      cerr << "There is no file like " << argv[1] << endl;
      return -2;
   }
   gf.write(out);   
   out.close();

   return 0;
}

This program reads file from local file system and send it to gridfs.
#include <mongo/client/dbclient.h>
#include <mongo/client/gridfs.h>

// g++ local_to_gridfs.cpp -lmongoclient -lboost_thread -lboost_filesystem -o local_to_gridfs

using namespace std;
using namespace mongo;

int main(int argc, const char **argv) { 
    char *data;
    int len;

    if (argc != 3) {
        cerr << "Usage " << argv[0] << " localFile remoteName "  << endl; 
        return -12;
    }

    fstream in(argv[1], ios::in|ios::binary|ios::ate);
    
    DBClientConnection c;
    c.connect("localhost"); 
    cout << "connected ok" <<endl;

    GridFS gfs = GridFS(c, "test", "testcpp");
    if ( in.is_open() ) {
        len = in.tellg();
        in.seekg( 0, ios::beg);
        data = new char[len];
        in.read(data, len);
    }
    //storing file

    gfs.storeFile(data, len, argv[2], "text/plain");
    delete [] data;
    cout << "file stored to gridfs" << endl;

    return 0;
}

No comments:

Post a Comment