samedi 17 octobre 2020

How to open file in c++ to write binary data into it?

Here i have got a write function which takes filename and i have got pointer to an array and i want to write that data into that file. write function works if i do anything execpt file handling. whenever i open file in that function it causes segmentation fault.

Bitmap::Bitmap(int width,int height)//:m_width(width),m_height(height),m_pPixel(new uint8_t [width*height*3]);
{
    m_width=width;
    m_height=height;
    m_pixeldata_ptr=new uint8_t [m_width*m_height*3]{0};
}

bool Bitmap::write(string filename)
{
    BitMapFileHeader fileHeader;
    BitMapInfoHeader infoHeader;
    
    fileHeader.fileSize = sizeof(BitMapFileHeader) + sizeof(BitMapInfoHeader) + m_width*m_height*3;
    fileHeader.dataOffest = sizeof(BitMapFileHeader) + sizeof(BitMapInfoHeader);
    
    infoHeader.width=m_width;
    infoHeader.height=m_height;
    
    //writing each 3 bit color to bitmap
    ofstream file;
    file.open(filename,ios::out);
    file.close();
    file.open(filename,ios::out | ios::binary);
    
    if(!file)//notice not operator is overloaded
    {
        return false;
    }
    
    m_width=800;
    m_height=600;
    
    file.close();
    
    file.write((char *)&fileHeader,sizeof(BitMapFileHeader));
    
    file.write((char *)&infoHeader,sizeof(BitMapInfoHeader));
    
    file.write((char *)m_pixeldata_ptr,m_width*m_height*3);
    
    
    file.close();
    
    
    return true;
}

Aucun commentaire:

Enregistrer un commentaire