Problem to check if file exists

I would like to see if a file exists. I did:
1
2
3
4
5
6
7
8
9
10
11
12

std::string path="C:\\Users\\"+ n +"\\Desktop\\file.txt;

std::ifstream myfile2;

if (!myfile2(path.c_str()))
    {
        std::cout << "File not exists" << std::endl;
        myfile.open(path.c_str());
        myfile <<"1";
        myfile.close();
    } 

But i get error:
error: no match for call to '(std::ifstream {aka std::basic_ifstream<char>}) (const char*)'
I think you can do

myfile.open(path.c_str());

if(myfile.is_open()) //then it exists

or myfile.good() may also work.

The trouble is that if you can't open it for another reason (permissions, for example) you may think it does not exist but it does. You will probably need to check an error condition to see if the problem is really nonexistence or something else if you want a really robust solution.

On UNIX-like systems you can use the stat() function. If stat() fails, check errno to see if it indicates that the file (or a component of the path) doesn't exist.
Topic archived. No new replies allowed.