Search code examples
c++filenumbersramgmp

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 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.


Solution

  • #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.