1

I want to make a program that lets user enter drive name/folder(C:\ or f:\folder\) and a file name (test.exe) then program searches that file in the given drive or folder and opens the file.I managed to do the function that opens the file but cannot figure out how to search the file pass the location of file found to open it. Can anyone help me?

herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
Amol Borkar
  • 2,321
  • 7
  • 32
  • 63
  • http://stackoverflow.com/questions/916973/recursive-file-search-using-c-mfc http://stackoverflow.com/questions/612097/how-can-i-get-a-list-of-files-in-a-directory-using-c-or-c – Sigcont Mar 19 '14 at 18:34
  • you can go through the following links: [Recursive file search using C++ MFC?][1] [How can I get a list of files in a directory using C or C++?][2] [1]: http://stackoverflow.com/questions/916973/recursive-file-search-using-c-mfc [2]: http://stackoverflow.com/questions/612097/how-can-i-get-a-list-of-files-in-a-directory-using-c-or-c – Sigcont Mar 19 '14 at 18:38

2 Answers2

2

You can use boost::file_system. Here is documentation: http://www.boost.org/doc/libs/1_55_0/libs/filesystem/doc/index.htm

EDIT: after some time, I've got that my ansver were sligtly out of topic. To check if file exists you can use special boost::filesystem function.

bool exists(const path& p);

/EDIT

And directory iterator example: http://www.boost.org/doc/libs/1_55_0/libs/filesystem/doc/tutorial.html#Directory-iteration

It that example used std::copy, but you need filenames. So you can do something like this.

#include <boost/filesystem.hpp>

namespace bfs = boost::filesystem;
std::string dirPath = "."; // target directory path
boost::filesystem::directory_iterator itt(bfs::path(dirPath)); // iterator for dir entries
for ( ; itt != boost::filesystem::directory_iterator(); itt++)
{
   const boost::filesystem::path & curP = itt->path();
   if (boost::filesystem::is_regular_file(curP)) // check for not-a-directory-or-something-but-file
   {
      std::string filename = curP.string(); // here it is - filename in a directory
      // do some stuff
   }
}

If you are not expirienced with boost - building it can be complicated. You can obtain prebuilded boost binaries for your compiller and platform at boost.teeks99.com

Also, if you cant use boost for some reason, there is platform specific ways of iterating a directory, but I dont know on which platform you are, so I cant provide you an example.

Vasilly.Prokopyev
  • 856
  • 1
  • 10
  • 24
-2

Try this:

char com[50]="ls ";
char path[50]="F:\\folder\\";
char file[50]="test.exe";

strcat(com,path);
strcat(com,file);

if (!system(com))  // system returns the return value of the command executed
    cout<<"file not present\n";
else
{
    cout<<"file is present\n";
    strcat(path,file);

    FILE* f = fopen(path,"r");

    //do your file operations here
}
HelloWorld123456789
  • 5,299
  • 3
  • 23
  • 33