如何在C 中读取一系列数据文件

How to read a sequence of data files in C++

本文关键字:一系列 数据 文件 读取      更新时间:2023-10-16

你好,我有150个数据文件,每个文件中都有4列。我想知道如何将数据读取到C 程序中。我已经尝试在线查找,但是我遇到的所有资源都只是有关如何从一个来源输入数据的教程。数据也是一个顺序的,这意味着我正在阅读的文本文件,具有" line_u1.txt" " line_u2.txt" 的格式>" line_u3.txt" ...,并且数据均一致地为:

column 1 = distances   
column 2 = X_values   
column 3 = Y_values   
column 4 = Z_values   

我想将这些数据导入C 程序,因为我尝试使用 MATLAB >,我认为数据是错误的,这就是为什么我要切换到C 程序,但是DON知道如何将150个数据文件读取到程序中。任何帮助将不胜感激。

根据此答案,C 17提供了一种在目录中获取所有文件的简便方法。

#include <string>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main() {
    std::string path = "/path/to/directory";
    for (auto & filepath : fs::directory_iterator(path))
        read_file(filepath); // You need to define this still
}

至于文件的实际读取,您应该能够使用您已经阅读的教程,但为了完整的答案

#include <fstream>
int distances = 0;
int x_values = 0;
int y_values = 0;
int z_values = 0;
void read_file(std::string filepath) {
    /* Might want to do checking here to make sure 
        the file is actually one you want to read in */
    std::ifstream infile(filepath);
    while (infile >> distance >> x >> y >> z) {
        distances += distance;
        x_values += x;
        y_values += y;
        z_values += z;
    }
}

在此答案中阅读更多文件。