如何在循环中写入时动态更改文件名?

Ric*_*nop 12 c

我想做这样的事情:在循环中,第一次迭代将一些内容写入名为file0.txt的文件,第二次迭代file1.txt等等,只需增加数量即可.

FILE *img;
int k = 0;
while (true)
{
            // here we get some data into variable data

    file = fopen("file.txt", "wb");
    fwrite (data, 1, strlen(data) , file);
    fclose(file );

    k++;

            // here we check some condition so we can return from the loop
}
Run Code Online (Sandbox Code Playgroud)

Joo*_*kia 15

int k = 0;
while (true)
{
    char buffer[32]; // The filename buffer.
    // Put "file" then k then ".txt" in to filename.
    snprintf(buffer, sizeof(char) * 32, "file%i.txt", k);

    // here we get some data into variable data

    file = fopen(buffer, "wb");
    fwrite (data, 1, strlen(data) , file);
    fclose(file );

    k++;

    // here we check some condition so we can return from the loop
}
Run Code Online (Sandbox Code Playgroud)


Pet*_*eUK 7

在C++中使用它的另一种方法:

#include <iostream>
#include <fstream>
#include <sstream>

int main()
{
    std::string someData = "this is some data that'll get written to each file";
    int k = 0;
    while(true)
    {
        // Formulate the filename
        std::ostringstream fn;
        fn << "file" << k << ".txt";

        // Open and write to the file
        std::ofstream out(fn.str().c_str(),std::ios_base::binary);
        out.write(&someData[0],someData.size());

        ++k;
    }
}
Run Code Online (Sandbox Code Playgroud)