1

I am writing a program in C++ which I need to save some .txt files to different locations as per the counter variable in program what should be the code? Please help

I know how to save file using full path

ofstream f;
f.open("c:\\user\\Desktop\\**data1**\\example.txt");
f.close();

I want "c:\user\Desktop\data*[CTR]*\filedata.txt"

But here the data1,data2,data3 .... and so on have to be accessed by me and create a textfile in each so what is the code? Counter variable "ctr" is already evaluated in my program.

kubudi
  • 658
  • 1
  • 9
  • 20
KB2807
  • 19
  • 1
  • 3

2 Answers2

2

You could snprintf to create a custom string. An example is this:

char filepath[100];
snprintf(filepath, 100, "c:\\user\\Desktop\\data%d\\example.txt", datanum);

Then whatever you want to do with it:

ofstream f;
f.open(filepath);
f.close();

Note: snprintf limits the maximum number of characters that can be written on your buffer (filepath). This is very useful for when the arguments of *printf are strings (that is, using %s) to avoid buffer overflow. In the case of this example, where the argument is a number (%d), it is already known that it cannot have more than 10 characters and so the resulting string's length already has an upper bound and just making the filepath buffer big enough is sufficient. That is, in this special case, sprintf could be used instead of snprintf.

Shahbaz
  • 46,337
  • 19
  • 116
  • 182
2

You can use the standard string streams, such as:

#include <fstream>
#include <string>
#include <sstream>
using namespace std;

void f ( int data1 )
{
     ostringstream path;
     path << "c:\\user\\Desktop\\" << data1 << "\\example.txt";
     ofstream file(path.str().c_str());
     if (!file.is_open()) { 
          // handle error.
     }
     // write contents...
}
André Caron
  • 44,541
  • 12
  • 67
  • 125