Search code examples
c++iostreambinaryfiles

Unable to write file in binary mode even with ios::binary


I followed the tutorial on cplusplus.com for std::ofstream::binary and cannot seem to get the hex output that I need in binary mode.

I currently need to do a project in cryptography and require the output to be in binary mode (and not writing the hex values into the contents of the file).

Below is an excerpt from my code (with comments):

ofstream writeout(filename2.c_str(), ios::binary);

//ctextvec is the vector that stores the ciphertext
for (int i=0; i<ctextvec.size(); i+=2)
{
    ostringstream oss, oss2;
    //formatting of hex to string (adding missing '0')
    oss << hex << setw(16) << setfill('0') << ctextvec[i];
    oss2 << hex << setw(16) << setfill('0') << ctextvec[i+1];

    //Stores all ciphertext characters as a string
    storestr.append(oss.str());
    storestr.append(oss2.str());
}

//Define new array to store characters for writing
char writearr[storestr.size()];
for(int i=0; i<storestr.size(); i++) writearr[i]=storestr[i];

//Perform write to file
for(int i=0; i<storestr.size(); i++)
    writeout.write((char*)&writearr[i],sizeof(char));
writeout.flush();
writeout.close();

I tried a lot of methods and all seemed to dump the contents into a file rather than writing into binary mode. I supposedly need this command to work to show that a file is encrypted (at least).

Below are the screenshots of the file that I got and what I should be getting.

What I'm getting: Content dump

What I'm supposed to get: Supposed output

Any help is much appreciated!


Solution

  • Most of your code is unnecessary, the for-lop even counterproductive.

    oss << hex << setw(16) << setfill('0') << ctextvec[i];
    

    This converts the binary number ctextvec[i] to a ASCII-hex representation. That's what you end up with in your file, eventually.

    char writearr[storestr.size()];
    for(int i=0; i<storestr.size(); i++) writearr[i]=storestr[i];
    

    You copy from a std::string which can give you the backing char array using c_str() to another char array, why?

    for(int i=0; i<storestr.size(); i++)
        writeout.write((char*)&writearr[i],sizeof(char));
    

    You write one byte at a time, why not just push the whole array to write?

    All you need to do is:

    ofstream writeout(filename2.c_str(), ios::binary);
    
    writeout.write(reinterpret_cast<char*>(ctextvec.data()), ctextvec.size() * sizeof(ctextvec[0]));
    
    writeout.close();
    

    This should do exactly what you want.