C++ 读取文件夹下 TXT 文件并保存为浮点数数组
C++ 读取文件夹下 TXT 文件并保存为浮点数数组
以下是一个示例代码,它使用了 C++17 标准库中的 filesystem 和 fstream 库来遍历文件夹并读取 txt 文件信息。它假设 txt 文件中只包含一个 float 值,每个文件名以 'data_' 开头,以 '.txt' 结尾。
#include <iostream>
#include <string>
#include <vector>
#include <filesystem>
#include <fstream>
int main()
{
std::string folder_path = "path/to/folder"; // 文件夹路径
std::vector<float> data; // 存储读取到的 float 数据
// 遍历文件夹
for (const auto& file : std::filesystem::directory_iterator(folder_path))
{
// 如果文件名以 'data_' 开头,并以 '.txt' 结尾
if (file.path().filename().string().find("data_") == 0 && file.path().extension() == ".txt")
{
// 打开文件
std::ifstream infile(file.path().string());
if (!infile.is_open())
{
std::cerr << "Failed to open file: " << file.path().string() << std::endl;
continue;
}
// 读取 float 值,假设 txt 文件中只包含一个 float 值
float value;
infile >> value;
if (infile.fail())
{
std::cerr << "Failed to read float value from file: " << file.path().string() << std::endl;
infile.close();
continue;
}
// 存储读取到的数据
data.push_back(value);
// 关闭文件
infile.close();
}
}
// 输出读取到的数据
for (const auto& d : data)
{
std::cout << d << std::endl;
}
return 0;
}
AI 优化版
原文地址:https://www.cveoy.top/t/topic/mJz6 著作权归作者所有。请勿转载和采集!