我有一個 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;
}
uj5u.com熱心網友回復:
你太努力了——你不需要先閱讀整個輸入,也不需要關心每一行的結構。
逐行讀寫,一次一百行。
沒有什么可讀的時候就停下來。
像這樣的事情應該這樣做:
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";
}
uj5u.com熱心網友回復:
您已經得到了答案,但我將提供一個使用std::copy_n,std::istream_iterator和的替代方案std::ostream_iterator。
這一次將 100 行復制到輸出當前輸出檔案。
我添加了一個包裝 a 的類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));
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/321781.html
