c ++将矢量元素写入拆分文件

c++ write vector elements to split files

假设我有一个 vector<string> lines,其中包含从文件中读取的所有行,那么我如何才能将向量的内容写回文件,除非将其拆分为每个文件的 x 行。我更喜欢分块问题而不是写回文件。例如

int offset = 10000;
std::vector<std::string> lines(27000);

...assuming lines has been initialized with lines

鉴于以上我应该

文件 1 : 10000

文件 2 : 10000

文件 3: 7000

很简单,你只需要一个循环和一个 if 语句。

ofstream output;
string filename = "filename";
int fileNum = 0;

for(int i = 0; i < vec.size(); ++i){
    if(i % 10000 == 0){
        if(output.is_open()) output.close();
        output.open(filename + to_string(++fileNum));
    }
    output << vec.at(i);
}

output.close();

这将在 "filename1"、"filename2" 和 "filename3" 中保存 27000 行文件的文件。

免责声明:徒手书写:可能包含语法错误。