Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

FileExists function

Status
Not open for further replies.

Bargaust

Programmer
Oct 20, 2002
2
GB
Can anyone tell me how I can find out whether a file exists on a given path? Something like this:

bool FileExists(char* FilePath) {
...
}
 
//i think a string would work just a well right?
//if it doesnt then just use an array of chars

#include <fstream.h>
#include <iostream.h>
#include <string>

bool fileexists(string filename);

void main()
{
string filename;
getline(cin,filename);
if (fileexists(filename))
cout << filename << &quot;exists.&quot; << endl;
else
cout << filename << &quot;does not exist.&quot; << endl;
}

bool fileexists(string filename)
{
ifstream infile;
infile.open(filename);
if (infile)
{
infile.close();
return true;
}
else
{
infile.close();
return false;
}
}

it *should* work, never done this exact thing before, but done stuff that checks to see if the file is there before it does anything, so i bet itd work
 
It will not work, infile != NULL allways.
There are a lot of ways to do it.
1)
#include <windows.h>
if(GetFileAttributes( PathName) == -1 ) {
//File not exists or no access - what is?
unsigned long dwerr = GetLastError();
if(dwerr == ERROR_SUCCESS || dwerr == ERROR_FILE_NOT_FOUND || dwerr == ERROR_PATH_NOT_FOUND || dwerr == ERROR_BAD_NETPATH) {
//File really not exists!
}
else {
//No access
}
}
2)
#include <io.h>
...
if(access(PathName, 0) == -1) {
//File not exists
}
3)
#include <stdio.h>
....
FILE * fl = fopen(PathName,&quot;rb&quot;);
if ( fl == NULL) {
//File not exists or no read access
}
else
fclose( fl); //Close handle
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top