vs2017 c++ 查找当前目录 后缀为 bin文件 代码
时间: 2024-03-14 19:44:07 浏览: 16
您可以使用以下代码来查找当前目录中后缀为 `.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++ 查找当前目录文件 代码
以下是在 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文件
要在 VS2017 中读取二进制文件,可以使用 C++ 的文件流(fstream)库。具体步骤如下:
1. 打开二进制文件
通过 fstream 的构造函数打开二进制文件,并指定打开模式为二进制模式(ios::binary)。
```c++
#include <fstream>
// 打开二进制文件
std::ifstream fin("example.bin", std::ios::binary);
if (!fin) {
// 打开文件失败
return -1;
}
```
2. 读取二进制文件
通过 fstream 的 read() 函数读取文件内容。
```c++
// 读取二进制文件
char buffer[1024];
fin.read(buffer, sizeof(buffer));
```
3. 关闭文件
操作完成后,一定要关闭文件。
```c++
// 关闭文件
fin.close();
```
完整的代码示例:
```c++
#include <fstream>
int main() {
// 打开二进制文件
std::ifstream fin("example.bin", std::ios::binary);
if (!fin) {
// 打开文件失败
return -1;
}
// 读取二进制文件
char buffer[1024];
fin.read(buffer, sizeof(buffer));
// 关闭文件
fin.close();
return 0;
}
```