PSXGamerPro1 PSXGamerPro1 - 3 months ago 14
C++ Question

Cannot Read Binary files in byte mode in C++

I am trying to read a binary file's data sadly opening in C++ is a lot different than in python for these things as they have byte mode. It seems C++ does not have that.

for (auto p = directory_iterator(path); p != directory_iterator(); p++) {
if (!is_directory(p->path()))
byte tmpdata;
std::ifstream tmpreader;
tmpreader.open(desfile, std::ios_base::binary);
int currentByte = tmpreader.get();
while (currentByte >= 0)
{
//std::cout << "Does this get Called?" << std::endl;
int currentByte = tmpreader.get();
tmpdata = currentByte;
}
tmpreader.close()
}
else
{
continue;
}


I want basically a clone of Python's methods of opening a file in
'rb'
mode. To have to actual byte data of all of the contents (which is not readable as it has nonprintable chars even for C++. Most of which probably cant be converted to signed chars just because it contains zlib compressed data that I need to feed in my DLL to decompress it all.

I do know that in Python I can do something like this:

file_object = open('[file here]', 'rb')


turns out that replacing the C++ Code above with this helps. However
fopen
is depreciated but I dont care.

What the Code above did not do was work because I was not reading from the buffer data. I did realize later that
fopen
,
fseek
,
fread
, and
fclose
was the functions I needed for read bytes mode ('rb').

for (auto p = directory_iterator(path); p != directory_iterator(); p++) {
if (!is_directory(p->path()))
{
std::string desfile = p->path().filename().string();
byte tmpdata;
unsigned char* data2;
FILE *fp = fopen("data.d", "rb");
fseek(fp, 0, SEEK_END); // GO TO END OF FILE
size_t size = ftell(fp);
fseek(fp, 0, SEEK_SET); // GO BACK TO START
data2 = new unsigned char[size];
tmpdata = fread(data2, 1, size, fp);
fclose(fp);
}
else
{
continue;
}

Answer
int currentByte = tmpreader.get();
while (currentByte >= 0)
{
    //std::cout << "Does this get Called?" << std::endl;
    int currentByte = tmpreader.get();
    //^ here!

You are declaring a second variable hiding the outer one. However, this inner one is only valid within the while loop's body, so the while condition checks the outer variable which is not modified any more. Rather do it this way:

int currentByte;
while ((currentByte = tmpreader.get()) >= 0)
{