循环浏览文件夹中的所有文件以继续执行脚本

Looping over all files in a folder to proceed script

本文关键字:文件 继续 执行 脚本 浏览 文件夹 循环      更新时间:2023-10-16

我附加了一个简化的C++代码,该代码从文件中读取数据,获得矢量的平均值,并将输出保存到csv中。文件我的问题是,我有100个文件,分别命名为test1.csv、test2.csv、…test100.csv,并递归地对100个文件执行相同的操作,并希望将每个输出分别保存为result1.cvs、result2.csv和…result100.csv。

坦率地说,我经常使用Matlab/R,这个循环很容易实现,但作为C++的初学者,我从一开始就感到困惑。

每个文件都有一个向量,包含不同的历史股价数据,具有相同长度的股价(如苹果、微软、IBM、通用汽车…)

以下是简化的代码供您参考,但实际的代码非常复杂,每个代码将生成25000*30000矩阵输出。

数据文件中的示例数据如下所示;45.7867.9087.1234.8934.6029.98……

感谢您提前提供的帮助。

#include <fstream>
#include <iostream>
int main() {
//std::ifstream infile ("E:\DATA\test1.txt");
std::ifstream infile ("E:\DATA\test1.csv");
float num;
float total = 0.0f;
unsigned int count = 0;
// While infile successfully extracted numbers from the stream
while(infile >> num) {
    total += num;
    ++count;
}
// don't need the file anymore, close it
infile.close();
// test to see if anything was read (prevent divide by 0)
if (!count) {
    std::cerr << "Couldn't read any numbers!" << std::endl;
    return 1;
}
// give the average
std::cout << "The average was: " << total/count << std::endl;
std::cout << "The sum was: " << total << std::endl;
std::cout << "The length was: " << count << std::endl;

// pause the console
// std::cin.sync();
//std::cin.get();
std::ofstream myfile;
myfile.open ("E:\DATA\result1.csv"); //check!!!!
myfile<<total/count<<",";  //Add "," for csc format
myfile.close();
std::cout << "average was sucessfully saved !!!! /n";
return 0;
}

//来源http://www.cplusplus.com/forum/general/124221/

听起来在for循环中运行这段代码最简单,每次迭代都会更新文件名字符串。例如:

#include <string>
#include <iostream>
#include <fstream>
int main() {
    for (int i = 1; i <= 100; i++) {
        std::string inFile;
        std::string outFile;
        // Add the prefix to the filename
        inFile.append("test");
        outFile.append("result");
        // Add the number to the filename
        inFile.append(std::to_string(i));
        outFile.append(std::to_string(i));
        // Add the suffix to the filename
        inFile.append(".csv");
        outFile.append(".csv");
        // std::cout << inFile << std::endl;
        // std::cout << outFile << std::endl;
        std::ifstream fin;
        std::ofstream fout;
        fin.open(inFile);
        fout.open(outFile); 
        // TODO:Use fin and fout
    }
    return 0;
}

如果你对此更满意,或者如果你只有一个旧版本的C++,你也可以用字符数组(C字符串)来做这件事,但概念是一样的。创建一个连接文件前缀、文件号和文件后缀的字符串,然后打开它,而不是硬编码文件名。