Check file existence with fstream using x86_64-w64-mingw32-g++ for cross compilation

I have a program that is written in C & C++ and I’m rewriting some parts to improve it. This program has to work with files, but I am not able to check if a file exists on Windows with a cross-compiled exe.

To check if my code was the problem, I have created this simple example:

#include <fstream>
#include <iostream>


int main(){
    std::fstream in_file("test.noexists", std::ios::in|std::ios::binary);

    if (in_file) {
        std::cout << "File exists" << std::endl;
    }
    else {
        std::cout << "File doesn't exists" << std::endl;
    }
}

Compiling this code using “x86_64-w64-mingw32-g++”, version 8.3-win32 on Debian 10, I’m unable to check if a file exists because it always returns “true”. To verify it I have compiled the same program on Linux using g++, and on Windows using mingw64, and both were working so looks like a problem building the project on Debian 10 mingw32.

I don’t know if my problem is a bug on Debian version or I am doing something wrong. Anyone knows anything about it?

The only difference I have seen between both, is the version (8.1 on Windows vs 8.3 on Debian), and of course the SO.

Thanks!.

EDIT:

I have upgraded to Debian 11 which has the x86_64-w64-mingw32-g++ v10 and same behavior. I forgot to say that I am using Debian 11 on WSL, not a real Debian distribution. I don’t think it matters.

EDIT2:

I have already seen the suggested thread, but the problem is that I want to use streams to manage the files and the only option in that thread also fails. Using any of the other three ways will be like a hack that will not help too much. I think that is not the best way to check the file presence with another example, and then reopen the file later to work with it.

Is supposed that the fstream class have boolean conversion as I have read in several threads and that is why I’m using this example. The Linux version works perfectly, so the function is working as expected. The problem is the Windows version compiled in Linux (cross compiled EXE).

I have tested in_file.good(), in_file.is_open(), in_file.bad(), just in_file… all of them returns like the file was open correctly. Also I have tried ifstream, but same behaviour.

Answer

Rest a bit always helps… I have found a workaround to my problem just reading 0 bytes.

#include <fstream>
#include <iostream>


int main(){
    std::fstream in_file("test.noexists", std::ios::in|std::ios::binary);

    char dummy;

    if (in_file.read(&dummy, 0)) {
        std::cout << "File exists " << in_file.tellg() << std::endl;
    }
    else {
        std::cout << "File doesn't exists" << std::endl;
    }
}

With this, even the cross compiled EXE works without problems.

I still thinking why only fails with the cross compiled EXE, but I was not able to find any info about it and how to fix it. At least this solution is working.

Best regards.