vs2017 c++ 查找当前目录文件 代码
时间: 2023-12-12 21:03:22 浏览: 29
以下是在 VS2017 中使用 C++ 查找当前目录文件的代码示例:
```c++
#include <iostream>
#include <filesystem>
namespace fs = std::experimental::filesystem;
int main()
{
std::cout << "Current directory: " << fs::current_path() << std::endl;
for (auto& file : fs::directory_iterator(fs::current_path()))
{
if (fs::is_regular_file(file))
{
std::cout << "File name: " << file.path().filename() << std::endl;
}
}
return 0;
}
```
这个程序首先输出当前目录,然后遍历当前目录的所有文件并输出它们的文件名。需要注意的是,`std::experimental::filesystem` 是 C++17 中引入的标准库,如果编译器不支持这个库,可以考虑使用 Boost.Filesystem 库。
相关问题
vs2017 c++ 查找当前目录 后缀为 bin文件 代码
您可以使用以下代码来查找当前目录中后缀为 `.bin` 的文件:
```c++
#include <iostream>
#include <fstream>
#include <filesystem>
#include <string>
namespace fs = std::filesystem;
int main()
{
const std::string extension = ".bin";
const fs::path currentDir = fs::current_path();
for (const auto& entry : fs::directory_iterator(currentDir))
{
if (entry.is_regular_file() && entry.path().extension() == extension)
{
std::cout << entry.path().string() << std::endl;
}
}
return 0;
}
```
这段代码使用了 C++17 中的文件系统库 `std::filesystem`,首先获取了当前目录路径,然后遍历当前目录中的每一个文件,如果该文件是一个普通文件并且后缀为 `.bin`,则将其路径输出到控制台中。
vs2017 C++获取运行目录路径
在 Visual Studio 2017 中,你可以通过以下代码获取 C++ 程序运行时的目录路径:
```cpp
#include <iostream>
#include <Windows.h>
using namespace std;
int main()
{
char path[MAX_PATH];
GetModuleFileName(NULL, path, MAX_PATH);
string::size_type pos = string(path).find_last_of("\\/");
cout << "当前程序运行目录:" << string(path).substr(0, pos) << endl;
return 0;
}
```
其中 `GetModuleFileName()` 函数可以获取当前程序的文件路径,然后由于文件路径与程序运行时的目录路径不同,需要对文件路径进行处理,得到程序运行时的目录路径。
这里使用 `string::find_last_of()` 函数查找最后一个目录分隔符,然后使用 `string::substr()` 函数截取字符串,得到程序运行时的目录路径。最后输出即可。
需要注意的是,这里使用了 Windows.h 头文件,因为 Visual Studio 2017 是在 Windows 系统下运行的。如果你使用的是其他操作系统,可能需要使用不同的库或函数来获取程序运行时的目录路径。