cpp写一个读取文件夹下txt文件信息并保存为float数组
以下是一个示例代码,它使用了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;
}
原文地址: https://www.cveoy.top/t/topic/bhK8 著作权归作者所有。请勿转载和采集!