【问题标题】:scan directory to find and open the file扫描目录以查找并打开文件
【发布时间】:2014-04-26 05:36:06
【问题描述】:

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

【问题讨论】:

标签: c++ file search directory


【解决方案1】:

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

编辑:一段时间后,我发现我的回答有点跑题了。要检查文件是否存在,您可以使用特殊的 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 - 构建它可能会很复杂。 您可以在 boost.teeks99.com 上为您的编译器和平台获取预构建的 boost 二进制文件

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

【讨论】:

【解决方案2】:

试试这个:

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
}

【讨论】:

  • ls &gt;在系统函数中有什么作用?
  • 更改了代码。它基本上将输出的内容写入文件。请参阅ls 命令。
  • 我试过打印文件存在但是怎么知道打开它的程序路径。
  • @EdwardMckinzie 如果文件的路径和名称以字符串形式存储,则将两者连接起来并编写系统命令。这就是你想要的吗?
  • @EdwardMckinzie 编辑了答案。你现在得到答案了吗?