C ++打开二进制文件

时间:2014-01-28 10:51:24

标签: c++ file binary

我想用C ++打开一个二进制文件。 但是我在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;
    }
}

我想做类似的东西:string OpenPacket(string filename) 但是不行:(

2 个答案:

答案 0 :(得分:2)

可能这是一个可能的包装函数:

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();
}

答案 1 :(得分:0)

我认为你需要这个:

    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;    
      }

供参考Check this

希望这会对你有所帮助。