1.11M Members

Check if file exist on current path

 
0
 

Hi,

I wanna ask you if there is SIMPLE way to check if file called XXX is in path YYY? I have this Code:

int GetLocation()
{
	GetName();
	string location;
	location += "C:\\Users\\" + name + "\\Documents\\test.txt";
	if(location)
		return 1;
	else
		return 0;
}

int main()
{
	if(GetLocation() == 1)
		Start();
	else
		ExitProcess(0);
	return 0;
}
 
1
 

You can try opening it for reading and check if it's open. If it's not open, it doesn't exist.

//...

#include <fstream>
#include <string>

//...

std::string filename;

//...

std::ifstream fin(filename.c_str());

if (fin.is_open()) { /* file exists */ }
else { /* file does not exist */ }

//...

Useful link -> http://cplusplus.com/doc/tutorial/files/

 
0
 

thanks,

I have one more question, does this works with other files? like .exe etc?

 
0
 

Yes. It works with any file. Though, it doesn't work with folders. Note that I suggested this because you asked for a simple way.
A more appropriate way to do this would be to use OS API functions -> http://msdn.microsoft.com/en-us/library/aa364418(v=vs.85).aspx

 
0
 

well, I'm totally confused when I read something at msdn, I'm just beginner and I really have no idea what that codes there means, so I don't wanna use them, and that thing with fstream works fine, so thanks! :)

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article