I wonder how to check If a file exist or not :
For Example I have many files :
Boba.txt
James.txt
Jamy.txt
Boby.txt
How can I check if the file starting with Bob exists ?
I wonder how to check If a file exist or not :
For Example I have many files :
Boba.txt
James.txt
Jamy.txt
Boby.txt
How can I check if the file starting with Bob exists ?
Note, I'm assuming that you're on a Windows system and that the files are in the same directory.
You can use the FindFirstFile and FindNextFile functions to iterate through a directory. The prefix can be included in search term.
Example
std::string strSearch = "C:\\Some Directory\\Bob*";
WIN32_FIND_DATAA ffd;
HANDLE hFind = FindFirstFileA(strSearch .c_str(), &ffd);
do
{
std::string strFile = ffd.cFileName;
}
while (FindNextFileA(hFind, &ffd) != 0);
Proper error checking and how to deal with directories is left as an exercise for the reader.
Assuming you need to do this within C++, the boost::filesystem
library can be very helpful. In that case, your problem can be solved by a variant of the solution posted here. In your case, you don't need a std::multimap
, but can just use simple std::string::find
.
You could open a file with fopen as read only "r"
. fopen will return a NULL pointer if the file does not exist. You can do this for any of the files needed by your program.
#include <cstdio>
int main ()
{
FILE **pFile;
pFile[0] = fopen ("Boba.txt","r");
pFile[1] = fopen ("Boby.txt","r");
if (pFile[0]!=NULL || pFile[1]!=NULL){
printf("File starting with \"bob\" exists.");
}
else printf("File does not exist.");
return 0;
}