Many times you would have come across a problem, in which some data has to be saved in a file repeatedly, say in a loop or something. If the data is different for each iteration, it would be desirable to create a new file for each different data. Let us take a case, for instance we are iterating over a video file, and we want to write each frame data in different text files like frame0.txt, frame1.txt, frame2.txt…. and so on. The file name would change in each iteration, so how can we change the name of file serially, without involving any user effort.

The answer is to use string builder which can combine different numeric and string data types into a single string. In C++, we have the std::stringstream class , while in C, we have the sprintf  function that we'll be taking advantage of.

The following C++ code shows how to achieve this using std::stringstream 

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


string directory = "D:/";
string fileName = "file";
string fileType = ".txt";

stringstream ss;

//Number of files
const int count = 5;

ofstream writer;

for(int i=0; i<count; i++)
{
    //Push all the parameters into the string stream
    ss<<directory<<fileName<<i<<fileType;
		
    writer.open(ss.str());

    /* Write Data */

    writer.close();

    //Clear the string stream
    ss.str("");
}

This code will create numbered files, but as the number of digits change, the length of file name will increase, e.g. after file9, it will create file10. If we want to keep the filename length same like instead of file9 we want file09, we have to modify how the variables are pushed into the stringstream like this:

#include<iomanip>
const int maxDigits = 4;
ss<<directory<<fileName<<setw(maxDigits)<<setfill<char>('0')<<i<<fileType;

This will append zeros before the file number, so now if the maximum number of digits is 4, files will be created like file0001, file0002, and so on. Both of the above mentioned operations can be achieved in C language also.

#include<stdio.h>

const char* directory = "D:/";
const char* fileName = "cfile";
const char* fileType = ".txt";

const int count = 5;

char name_buffer[512];
FILE* f = NULL;

int i;

for(i=0; i<count; i++)
{
    //Print to character buffer
    sprintf(name_buffer,"%s%s%d%s",directory,fileName,i,fileType);

    f = fopen(name_buffer,"w");

    /* Write Data */

    fclose(f);
}

You can download this working code to integrate into your exiting C, C++ applications.