Search code examples
c++g++cygwinc++20visual-studio-2022

MSVC compiled executable for same code cant read a file, MINGW compiled executable can read the same


#include <iostream>
#include <fstream>

using namespace std;
int main() {
    ifstream infile {"asio-1.28.0.zip", ios_base::in};
    char buf[512];
    bool done = false;
    while ((!done) && (infile.rdstate() == ios::goodbit)) {
        infile.read(buf, 512);
        cout << infile.rdstate() << endl;
        size_t len = infile.gcount();
        if (len < 512) done=true;
        cout <<"Read " << len << " chars\n";
    }
    if (infile.eof()) {
        cout << "Found eofbit\n";
    }
    if (infile.fail()) {
        cout << "Found failbit\n";
    }
    if (infile.bad()) {
        cout << "Found badbit\n";
    }
    return 0;
}

the above code when compiled on cygwin with g++ (GCC) 11.3.0

$g++ --std=c++20 file_read_write.cpp -o file_read_write_gcc.exe

prints out the entire file and then gets the eofbit and failbit But the same code compiled with MSVC from Visual Studio 2022

cl /std:c++20 file_read_write.cpp

stops printing after 414 characters and gets the eofbit and failbit.

The asio zip file is the same file downloaded from asio website. Is this likely a compiler bug or am I missing something.

I expect both the executable to work in the same way since the code is same and I am using C++20 on both compilers.


Solution

  • As Retired Ninja said, open the file in binary mode

     ifstream infile{ "asio-1.28.0.zip",  std::ios::binary };