Richard Knop
Richard Knop

Reputation: 83745

How to dynamically change filename while writing in a loop?

I would like to do something like this: In a loop, first iteration write some content into a file named file0.txt, second iteration file1.txt and so on, just increase the number.

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
}

Upvotes: 19

Views: 41650

Answers (5)

Josh Wieder
Josh Wieder

Reputation: 186

I accomplished this in the manner below. Note that unlike a few of the other examples, this will actually compile and function as intended by without any modification beside preprocessor includes. The solution below iterates fifty filenames.

int main(void)
{
    for (int k = 0; k < 50; k++)
    {
        char title[8];
        sprintf(title, "%d.txt", k);
        FILE* img = fopen(title, "a");
        char* data = "Write this down";
        fwrite (data, 1, strlen(data) , img);
        fclose(img);
    }
}

Upvotes: 1

PeteUK
PeteUK

Reputation: 1112

A different way to do it in 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;
    }
}

Upvotes: 7

Jookia
Jookia

Reputation: 6890

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
}

Upvotes: 21

AndersK
AndersK

Reputation: 36102

so create the filename using sprintf:

char filename[16]; 
sprintf( filename, "file%d.txt", k );  
file = fopen( filename, "wb" ); ...

(although that is a C solution so the tag is not correct)

Upvotes: 2

Nils Pipenbrinck
Nils Pipenbrinck

Reputation: 86393

FILE *img;
int k = 0;
while (true)
{
    // here we get some data into variable data
    char filename[64];
    sprintf (filename, "file%d.txt", k);

    file = fopen(filename, "wb");
    fwrite (data, 1, strlen(data) , file);
    fclose(file );
    k++;

            // here we check some condition so we can return from the loop
}

Upvotes: 2

Related Questions