简体   繁体   English

C ++ - 按顺序打开文本文件

[英]C++ - Opening text files sequentially

I have hundreds of .txt files ordered by number: 1.txt, 2.txt, 3.txt,...n.txt. 我有数百个按文件排序的.txt文件:1.txt,2.txt,3.txt,... n.txt。 In each file there are two columns with decimal numbers. 在每个文件中有两列带有十进制数字。 I wrote an algorithm that does some operations to one .txt file alone, and now I want to recursively do the same to all of them. 我编写了一个算法,只对一个.txt文件执行一些操作,现在我想以递归方式对所有文件执行相同操作。 This helpful question gave me some idea of what I'm trying to do. 这个有用的问题让我对我正在尝试做的事情有所了解。 Now I'm trying to write an algorithm to read all of the files: 现在我正在尝试编写一个算法来读取所有文件:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () 
{
int i, n;
char filename[6];
double column1[100], column2[100];
for (n=1;n=200;n++)
{
sprintf(filename, "%d.txt", n);
ifstream datafile;
datafile.open(filename);
    for (i=0;i<100;i++)
    {
    datafile >> column1[i] >> column2[i];
    cout << column1[i] << column2[i];
    }
datafile.close();
}
return 0;
}

What I think the code is doing: it is creating string names from 1.txt till 200.txt, then it opens files with these names. 我认为代码正在做什么:它是从1.txt到200.txt创建字符串名称,然后它打开带有这些名称的文件。 For each file, the first 100 columns will be associated to the arrays column1 and column2, then the values will be shown on the screen. 对于每个文件,前100列将与数组column1和column2相关联,然后这些值将显示在屏幕上。 I don't get any error when compiling it, but when I run it the output is huge and simply won't stop. 编译时我没有收到任何错误,但是当我运行它时输出很大并且根本不会停止。 If i set the output to a .txt file it reaches easily some Gb! 如果我将输出设置为.txt文件,它很容易达到一些Gb! I also tried decreasing the loop number and reduce the numbers of columns (to 3 or so), but I till get an infinite output. 我也试过减少循环次数并减少列数(到3左右),但我得到无限输出。 I would be glad if someone could point the mistakes I'm doing in the code... I am using gcc 5.2.1 with Linux. 如果有人能指出我在代码中所犯的错误,我会很高兴...我正在使用gcc 5.2.1和Linux。 Thanks! 谢谢!

  • 6-element array is too short to store "200.txt" . 6元素数组太短,无法存储"200.txt" It must be at least 8 elements. 它必须至少8个元素。
  • The condition n=200 is wrong and is always true. 条件n=200是错误的并且始终为真。 It should be n<=200 . 它应该是n<=200

If all your files are in the same directory, you could also use boost::filesystem , eg: 如果您的所有文件都在同一目录中,您还可以使用boost::filesystem ,例如:

auto path = "path/to/folder";
std::for_each(boost::filesystem::directory_iterator{path},
        boost::filesystem::directory_iterator{},
        [](boost::filesystem::directory_entry file){
            // test if file is of the correct type
            // do sth with file
        });

I think this is a cleaner solution. 我认为这是一个更清洁的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM