Search code examples
c++binaryfilesifstream

When reading in a binary file as a char * buffer, it keep reading it as binary instead of as characters


void reader(string fileName){
     ifstream ifile; 
     ifile.open(fileName, ios::binary | ios::in);
     ifile.seekg (0, ifile.end);
     int length = ifile.tellg();
     ifile.seekg (0, ifile.beg);
     char * buffer = new char [length];
while(ifile.good()){

    // read data as a block:
    ifile.read (buffer,4);
    cout << buffer <<endl;
    //ifile.read((char *)&inputName, sizeof(int));
    //cout << inputName;

}
ifile.close();

The output it gives out looks like this:

▒d▒▒root.d[$Apd▒▒
endXroot.d

when I expect it to look more like

root.d
endXroot.d

the data was entered into the file as root.d/0endXroot.d idk if that helps or not.


Solution

  • ifstream ifile; 
        ifile.open(fileName, ios::binary | ios::in |ios::ate);
        if(ifile.good()){
            char * buffer;
            long size;
            ifstream file (fileName, ios::in|ios::binary|ios::ate);
            size = file.tellg();
            file.seekg (0, ios::beg);
            buffer = new char [size];
            file.read (buffer, size);
        }
     }
    

    I fixed it by having it get the size and then reading directly to it. I also fixed underlying issues with how the write was written for the binary file.