Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically change filename while writing in a loop?

Tags:

c

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
}
like image 774
Richard Knop Avatar asked Nov 20 '10 13:11

Richard Knop


2 Answers

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
}
like image 51
Jookia Avatar answered Oct 14 '22 18:10

Jookia


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;
    }
}
like image 24
PeteUK Avatar answered Oct 14 '22 16:10

PeteUK