Hey guys, Just need a quick little bit of help. How do you check if a file exists or not? I tried this...
it didn't work.Code:...
if(ifstream ("filename")==0)
{
cout<<"File Exists!";
}
...
Thanks guys
Printable View
Hey guys, Just need a quick little bit of help. How do you check if a file exists or not? I tried this...
it didn't work.Code:...
if(ifstream ("filename")==0)
{
cout<<"File Exists!";
}
...
Thanks guys
I believe it works like this:
Code:ifstream myFile("Something.txt");
if (!myFile){
cout << "\n Failed to open file.";}
else{
cout << "\n Success.";}
Or you can use is_open().
Code:ifstream myFile("filename");
if(myFile.is_open())
{
cout<<"File Exists!";
}
Or the exists() call from the CRT, which doesn't care if you actually have read permission on the file.
or if you are using windows you can use PathFileExists()
I had some problems using PathFileExists();
What header file is this declared in?Code:#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
if (PathFileExists("Data.txt") == 0)
{
cout << "File Found "<<endl;
}
else
{
cout << "File Not Found " <<endl;
}
cin.get();
}
Everything you ever wanted to know about PathFileExists, but were afraid to ask.
What you meant to say was:Quote:
Originally Posted by Ken Fitlike
Everything you ever wanted to know about PathFileExists, but were too ........ing lazy to search for!
Quzah.
Code:#include <iostream>
#include <windows.h>
#include <shlwapi.h>
#pragma comment(lib,"shlwapi.lib")
using namespace std;
int main()
{
int A = PathFileExists("data.txt");
if (A == 1)
{
cout << "File Found "<<endl;
}
else
{
cout << "File Not Found " <<endl;
}
cin.get();
return 0;
}
Careful, I believe
is compiler specific and will not work in all cases.Quote:
#pragma comment(lib,"shlwapi.lib")
*edit - oops didn't mean to bump the thread. I didn't realize it was so old. *
Thread wasn't old.
This pragma is indeed compiler-specific. But then, PathFileExists is itself platform-specific.