扫描目录查找并打开文件

scan directory to find and open the file

本文关键字:文件 查找 扫描      更新时间:2023-10-16

我想制作一个程序,让用户输入驱动器名称/文件夹(C:f:folder)和文件名(test.exe),然后程序在给定的驱动器或文件夹中搜索该文件并打开该文件。我设法做了打开文件的功能,但无法弄清楚如何搜索文件,通过找到打开它的文件的位置。有人能帮我吗?

可以使用boost::file_system。这里是文档:http://www.boost.org/doc/libs/1_55_0/libs/filesystem/doc/index.htm

EDIT:一段时间后,我发现我的答案有点跑题了。要检查文件是否存在,可以使用特殊的boost::filesystem函数。

bool exists(const path& p);

/编辑

和目录迭代器示例:http://www.boost.org/doc/libs/1_55_0/libs/filesystem/doc/tutorial.html#Directory-iteration

如果这个例子使用了std::copy,但是你需要文件名。所以你可以这样做

#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
   }
}

如果你没有增强的经验,它可以是复杂的。您可以在boost.teeks99.com

获取编译器和平台的预构建boost二进制文件。

同样,如果你因为某种原因不能使用boost,有特定于平台的方法来迭代目录,但我不知道你是哪个平台,所以我不能给你一个例子。

试试这个:

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 presentn";
else
{
    cout<<"file is presentn";
    strcat(path,file);
    FILE* f = fopen(path,"r");
    //do your file operations here
}