开发者

How do I read X file into RAM as a number in C++ in a linux environment?

I'm working on a compression program which needs to read a file into RAM as a single 开发者_C百科number and perform basic math operations and bit shifting. I've looked at gmp from GNU, but that has such poor integration into c/c++ I have no idea where to begin to read and put the values into the mpz_t variable.


#include <fstream>
#include <gmp.h>
#include <gmpxx.h>
#include <iostream>

using namespace std;

mpz_class fileToNumber (const string& fileName)
{
    mpz_class number;
    ifstream file(fileName.c_str());
    while( file.good() ){
        unsigned char c;
        file >> c;
        number <<= 8;
        number += c;
    }
    file.close();
    return number;
}


int main (int argc, char* argv[])
{
    if( argc - 1 < 1 ){
        cout << "Usage: " << argv[0] << " file.txt" << endl;
        return 0;
    }
    cout << hex << fileToNumber(argv[1]) << endl;
}

Edit: Fixed, misunderstood the original question, now it reads files as a number instead of an ASCII number.

Edit: Moved the entire file to mpz_class conversion into a nice function.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜