扫描目录查找并打开文件
scan directory to find and open the file
我想制作一个程序,让用户输入驱动器名称/文件夹(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
}
相关文章:
- 在C++中查找文件
- 在UNIX系统中使用DIR查找文件的字节大小
- 使用gcc从静态链接的文件中查找可选符号
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- 如何在文件中查找字节序列
- FFMpeg库:如何在音频文件中精确查找
- C++ 使用存储在动态数组中的文本文件中的数据查找模式
- g++ -I 和 -L 命令来查找不起作用的 .hpp 文件
- 查找定义我的 C/C++ 函数/宏的文件比'grep'更简单的方法
- 从文件中查找单词并替换到其他文件中
- 如何从文本文件中查找最常见的字母和出现次数?
- 在代码块中查找输出文件
- 在终端中运行可执行文件与在Mac查找器中打开
- 在链接可执行文件之前查找静态库未解析的依赖项
- 在 elf 文件中查找全局变量的位置
- 在目录中查找所有.cpp.h文件(include,src等)的传统方法
- 查找第一个文件/查找下一个文件不返回文件夹中的所有文件
- C++/哪个文件查找顺序更快
- 在内存中创建gzip文件查找CPP示例
- 使用c++和文件查找曲线下的面积