簡體   English   中英

如何從C ++中的文本文件寫入多個文本文件?

[英]How to write multiple text files from a text file in C++?

我有一個 txt 文件,有 500,000 行,每行有 5 列。 我想從此文件中讀取數據並將其寫入不同的 5000 個 txt 文件,每個文件有 100 行,從輸入文件的第一行到最后一行。 此外,文件名與訂單號一起輸出,比如“1_Hello.txt”,它有第 1 行到第 100 行,“2_Hello.txt”,它有第 101 行到第 200 行,依此類推,直到“5000_Hello.txt”。 txt”,其中包含第 499901 行到第 500000 行。

我曾經運行以下代碼來編寫少於10個文件的文件。 但是在 5000 個文本文件的情況下我怎么寫呢? 任何幫助,將不勝感激。

 #include <iostream>
 #include <fstream>
 #include <vector>
 using namespace std;

 int main() {

 vector<string> VecData;
 string data;

 ifstream in("mytext.txt");
 while (in >> data) {
    VecData.push_back(data);
 }
 in.close();


 ofstream mynewfile1;
 char filename[]="0_Hello.txt";

 int i, k=0, l=0;
 while(l<VecData.size()){
    for(int j='1';j<='3';j++){            
        filename[0]=j;
        mynewfile1.open(filename);
        for( i=k; i<k+((int)VecData.size()/3);i+=5){
            mynewfile1<<VecData[i]<<"\t";
            mynewfile1<<VecData[i+1]<<"\t";
            mynewfile1<<VecData[i+2]<<"\t";
            mynewfile1<<VecData[i+3]<<"\t";
            mynewfile1<<VecData[i+4]<<endl;
        }
        mynewfile1.close();
        l=i;
        k+=(int)VecData.size()/3; 
    }
 }

 cout<<"Done\n";
 return 0;
}

你太努力了——你不需要先閱讀整個輸入,也不需要關心每一行的結構。

逐行讀寫,一次一百行。
沒有什么可讀的時候就停下來。

像這樣的事情應該這樣做:

int main()
{
    std::ifstream in("mytext.txt");
    int index = 0;
    std::string line;
    while (in)
    {
        std::string name(std::to_string(index) + "_Hello.txt");
        std::ofstream out(name);
        for (int i = 0; i < 100 && std::getline(in, line); i++)
        {
            out << line << '\n';
        }
        index += 1;
    }
    cout << "Done\n";
}

你已經得到了答案,但我會給出一個使用std::copy_nstd::istream_iteratorstd::ostream_iterator的替代方案。

這一次將 100 行復制到輸出當前輸出文件。

我添加了一個包裝std::string的類,以便能夠為std::string提供我自己的流操作符,使其一次讀取一行。

#include <algorithm>
#include <fstream>
#include <iostream>

struct Line {
    std::string str;
};

std::istream& operator>>(std::istream& is, Line& l) {
    return std::getline(is, l.str);
}

std::ostream& operator<<(std::ostream& os, const Line& l) {
    return os << l.str << '\n';
}

int main() {
    if(std::ifstream in("mytext.txt"); in) {
        for(unsigned count = 1;; ++count) {

            // Constructing an istream_operator makes it read one value from the stream
            // and if that fails, it'll set the eofbit on the stream.

            std::istream_iterator<Line> in_it(in);
            if(!in) break; // EOF - nothing more in the input file

            // Open the output file and copy 100 lines into it:
            if(std::ofstream out(std::to_string(count) + "_Hello.txt"); out) {
                std::copy_n(in_it, 100, std::ostream_iterator<Line>(out));
            }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM