checking file fail

1
2
3
4
5
6
7
8
        ofstream infile;
	infile.open("Input.txt");
	if(infile.fail())
	{
		cout << "Error Opening File in Input" << endl;
		system("pause");
		exit(1);
	}


So i'm trying to see if it fails, but if i change "Input" name would the computer just create a new file name of it for example if i change "Input" to "asdf" the computer is just going to create "asdf" how do i fix it. Thanks!
From "Input.txt" I assume that you're going to read from that file, right? If so, ofstream should be replaced with ifstream

ofstream and "Input" seems like an oxymoron to me, since "Ofstream is output stream class to operate on files"
Last edited on
Whenever i put ifstream it gives me a error.
When your file "Input.txt" is created already and you open it for reading, no error should be raised. But make sure that file path is correct.
I had to check for a file at some point and found this lying on the net somewhere.
Would like to give credit to whomever made it but cant remember the name.
anyhow this checks if file exists. i think :)

1
2
3
4
5
6
7
8
9
10
11
12
#include <sys/stat.h>

bool fileExists(const std::string& filename)
{
    struct stat buf;
    if (stat(filename.c_str(), &buf) != -1)
    {
        return true;
    }
    return false;

}

Topic archived. No new replies allowed.