how to check whether a file exists or not

my application is present in a folder called file which contains user interface, header files and .cpp files
kindly suggest me how to check whether any file exists in my folder, if it exists then it should open in read only mode, if it does not exists then create a new file.

since am a beginner may i expect the suggestion in a step wise order with an example
Well, the C++ standard lib doesn't contain any function that does that. The POSIX lib and winapi are examples of libraries that do have such a function. I'll post examples. Note that usually the windows api is only available on windows and posix is available on OS X, most linux distros and a very old version on windows (I don't know if the function to check if a file exists is available).
You can do the following with the winapi:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <Windows.h>
#include <iostream>

using namespace std;

bool exists(char* filePath)
{
	//This will get the file attributes bitlist of the file
	DWORD fileAtt = GetFileAttributesA(filePath);

	//If an error occurred it will equal to INVALID_FILE_ATTRIBUTES
	if(fileAtt == INVALID_FILE_ATTRIBUTES)
		//So lets throw an exception when an error has occurred
		throw GetLastError();

	//If the path referers to a directory it should also not exists.
	return ( ( fileAtt & FILE_ATTRIBUTE_DIRECTORY ) == 0 ); 
}

int main()
{
	if (exists("test.txt"))
		cout << "test.txt exists!\n";
	else
		cout << "test.txt does not exists!\n";

	return 0;
}

You can do the following with POSIX:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <sys/stat.h>
#include <iostream>

using namespace std;

bool exists(char* filePath)
{
	//The variable that holds the file information
	struct stat fileAtt; //the type stat and function stat have exactly the same names, so to refer the type, we put struct before it to indicate it is an structure.

	//Use the stat function to get the information
	if (stat(filePath, &fileAtt) != 0) //start will be 0 when it succeeds
		throw errno; //So on non-zero, throw an exception
	
	//S_ISREG is a macro to check if the filepath referers to a file. If you don't know what a macro is, it's ok, you can use S_ISREG as any other function, it 'returns' a bool.
	return S_ISREG(statistics.st_mode);
}

int main()
{
	if (exists("test.txt"))
		cout << "test.txt exists!\n";
	else
		cout << "test.txt does not exists!\n";

	return 0;
}
Last edited on
Any questions? Just say so.
Boost.Filesystem has an exists predicate:
http://www.boost.org/doc/libs/1_42_0/libs/filesystem/doc/index.htm
Topic archived. No new replies allowed.