Creating file names automatically C ++

I am trying to write a C ++ program that creates some files (.txt) and writes the result to them. The problem is that the number of these files is not fixed at the beginning and appears only at the end of the program. I would call these files "file_1.txt", "file_2.txt", ..., "file_n.txt", where n is an integer.

I cannot use concatenation because the file name requires the type "const char *", and I have not found a way to convert "string" to this type. I did not find an answer over the Internet and I will be very happy if you help me.

+4
source share
5 answers

You can get const char* from std::string using the c_str function.

 std::string s = ...; const char* c = s.c_str(); 

If you do not want to use std::string (perhaps you do not want to do memory allocation), you can use snprintf to create a formatted string:

 #include <cstdio> ... char buffer[16]; // make sure it big enough snprintf(buffer, sizeof(buffer), "file_%d.txt", n); 

n here is the number in the file name.

+5
source
  for(int i=0; i!=n; ++i) { //create name std::string name="file_" + std::to_string(i) + ".txt"; // C++11 for std::to_string //create file std::ofstream file(name); //if not C++11 then std::ostream file(name.c_str()); //then do with file } 
+5
source

... another way to reset the file name

 #include <sstream> int n = 3; std::ostringstream os; os << "file_" << n << ".txt"; std::string s = os.str(); 
+1
source

Code example:

 #include <iostream> #include <fstream> #include <string> #include <sstream> using namespace std; string IntToStr(int n) { stringstream result; result << n; return result.str(); } int main () { ofstream outFile; int Number_of_files=20; string filename; for (int i=0;i<Number_of_files;i++) { filename="file_" + IntToStr(i) +".txt"; cout<< filename << " \n"; outFile.open(filename.c_str()); outFile << filename<<" : Writing this to a file.\n"; outFile.close(); } return 0; } 
0
source

I use the following code for this, you may find this useful.

 std::ofstream ofile; for(unsigned int n = 0; ; ++ n) { std::string fname = std::string("log") + std::tostring(n) << + std::string(".txt"); std::ifstream ifile; ifile.open(fname.c_str()); if(ifile.is_open()) { } else { ofile.open(fname.c_str()); break; } ifile.close(); } if(!ofile.is_open()) { return -1; } ofile.close(); 
0
source

Source: https://habr.com/ru/post/1442600/


All Articles