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).
#include <Windows.h>
#include <iostream>
usingnamespace 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;
}
#include <sys/stat.h>
#include <iostream>
usingnamespace 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;
}