mardi 21 août 2018

C++ - Can't write byte on a file in binary mode

I have a problem with this little piece of code. I'm new to C++ and I need to understand how to write a byte (or a multiple bytes) inside a file in binary mode.

With this code I read the first 2048 bytes of a file and show them on the console. If I remove the first file.close() and the second file.open() I can't write into file. If I use the code like the one reported below I can write a byte (E4) at the index 0 of the file but if I execute the same code again I can't see another E4 at the beginning of the file? Why? Thanks

#include <iostream>
#include <string>
#include <fstream>

int main()
{
    string workingDirectory = "C:\\Users\\francesco\\Documents\\Test\\";
    string inputFile = workingDirectory + "track.iso";
    fstream file;
    file.open(inputFile, ios_base::in | ios_base::out | ios_base::binary);
    char *buffer = new char [2352];
    file.read(buffer, 2048);

    cout << "Track:" << endl;
    for (int i = 0; i < 2048; i++)
    {
        cout << buffer[i];
    };

    cout << endl;
    delete[] buffer;

    file.close();

    int num = 228; //hex E4
    file.open(inputFile, ios_base::in | ios_base::out | ios_base::binary);
    file.write((char*)&num, sizeof(num));
    file.close();

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire