Hi,
I want a function to check or search if a certain file exists or not?
Anyone have Idea about such function in C++?
Regards,
Hi,
I want a function to check or search if a certain file exists or not?
Anyone have Idea about such function in C++?
Regards,
The following code is an example of how to use stat to check if a file exists. Note the comments which show you where this function could be extended if more details are required.
Using stat is also portable between operating systems and therefore you should be able to use this same code on Linux, Windows, Unix, Solaris, etc. The only thing that may differ between operating systems and compilers is the name of the include file (even though it shouldn't change).Code:#include <sys/stat.h> bool FileExists(string strFilename) { struct stat stFileInfo; bool blnReturn; int intStat; // Attempt to get the file attributes intStat = stat(strFilename.c_str(),&stFileInfo); if(intStat == 0) { // We were able to get the file attributes // so the file obviously exists. blnReturn = true; } else { // We were not able to get the file attributes. // This may mean that we don't have permission to // access the folder which contains this file. If you // need to do that level of checking, lookup the // return values of stat which will give you // more details on why stat failed. blnReturn = false; } return(blnReturn); }
The best bet is just open the file and ask if the file is _really_ opened. With streams you can do just this:
Later you can use the return value of is_open(), to try find the cause of the error. For example, if the drive was a:\, you can ask if there is a diskette in the drive.Code:fstream myfile; myfile.open(<path_and_name>, ios::read); if (myfile.is_open()) //the file is opened else //the file was not opened --> something happens! myfile.close();
Use FileExists function. If file exists, then this function will return True.
Code:procedure TForm1.Button1Click(Sender: TObject); begin if FileExists(Edit1.Text) then ShowMessage('File already exists!') else ShowMessage('This file is unique'); end;
just open the file for reading, if this succeeds, then the file exists, something like this:
Code:FILE* fp = fopen(path, "r"); if (fp) { // file exists fclose(fp); } else { // file doesn't exist }
Bookmarks