1

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 ?

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
predictive
  • 33
  • 1
  • 7

3 Answers3

2

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.

Ralara
  • 559
  • 4
  • 19
0

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.

Community
  • 1
  • 1
KyleKnoepfel
  • 1,426
  • 8
  • 24
0

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; 
}
Michael LeVan
  • 528
  • 2
  • 8
  • 21
  • Your code is writing to an invalid memory space: you haven't reserved space for pFile items, yet you're using them. The code is so small that it didn't cause any major problems, but it could in larger projects. – JACH Dec 28 '20 at 19:19
  • I appreciate your comment. It is fair. Thank you. – Michael LeVan Jun 16 '21 at 16:32