简体   繁体   English

是否可以在C ++中创建大量txt文件?

[英]Is it possible to create bulk of txt files in c++?

I want to create thousands of file with txt extension in c++. 我想在C ++中创建成千上万个带有txt扩展名的文件。 Is it possible? 可能吗? I can not imagine how can i do that. 我无法想象我该怎么做。 If I write some code right here so you can understand what I want. 如果我在这里编写一些代码,以便您了解我想要的内容。

int main () 
{
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}

I want to generate a bulk of txt of files with this method. 我想用这种方法生成大量的txt文件。 In addition I want to run these codes inside a for structure. 另外,我想在for结构中运行这些代码。 At the end of the operation I must have 10,000 file and these file's names are like example1.txt , example2.txt , example3.txt ... You do not have to write code I just want to know how to do it. 在操作结束时,我必须有10,000个文件,这些文件的名称类似于example1.txt,example2.txt,example3.txt...。您不必编写代码,我只想知道该怎么做。 You can just share link to some tutorial. 您可以只共享一些教程的链接。

Yes, you can do that. 是的,你可以这么做。 Here are the steps I suggest: 这是我建议的步骤:

  1. Use a for or a while loop. 使用forwhile循环。

  2. In each iteration of the loop construct the name of a unique file by using the loop counter. 在循环的每次迭代中,使用循环计数器构造唯一文件的名称。 You can use std::ostringstream or sprintf for that. 您可以使用std::ostringstreamsprintf

  3. Use the code you already have to create a file in each iteration of the loop. 使用您已经在循环的每次迭代中创建文件的代码。

#include <fstream>
#include <iostream>

int main () {

    std::ofstream myfile;
    for(int i=1;i<=1000;i++){

        myfile.open("example" + std::to_string(i) + ".txt");
        myfile << "Writing this to a file.\n";
        myfile.close();
    }
    return 0;
}

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

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