user3080385
user3080385

Reputation:

C++ Opening a binary file

I want to open a binary file in C++. but I have this function in C:

uint openPacket(const char* filename, unsigned char** buffer) {
    FILE* fp = fopen(filename, "rb");
    if (fp) {
        size_t result;
        fseek(fp, 0, SEEK_END);
        long fsize = ftell(fp);
        rewind(fp);
        *buffer = new unsigned char[fsize];
        result = fread(*buffer, 1, fsize, fp);
        if (result != fsize) {
            printf("Reading error in %s, unable to send packet!\n", filename);
            delete[] * buffer;
            fsize = 0;
        }
        fclose(fp);
        return fsize;
    } else {
        printf("Couldn't open %s for packet reading, unable to send packet!\n", filename);
        return 0;
    }
}

I want to make something like: string OpenPacket(string filename) but don't work :(

Upvotes: 0

Views: 366

Answers (2)

A B
A B

Reputation: 1521

I think You Need this:

    uint openPacket(const char* filename, unsigned char** buffer) {
    ifstream file (filename, ios::in|ios::binary|ios::ate);
    streampos size;
   if (file.is_open())
      {
        size = file.tellg();
        *buffer = new char [size];
        file.seekg (0, ios::beg);
        file.read (memblock, size);
        file.close();

        cout << "the entire file content is in memory";
        return size;    
      }

For reference Check this

hope this will help you.

Upvotes: 0

αλεχολυτ
αλεχολυτ

Reputation: 5060

May be this is a possible wrapper function:

std::string openPacket( const std::string& filename )
{
    unsigned char* buff;
    uint size = openPacket( filename.c_str(), &buff );
    if( size )
    {
        std::string s( reinterpret_cast<const char*>(buff), size );
        delete [] buff;
        return s;
    }
    return std::string();
}

Upvotes: 2

Related Questions