Creating file names automatically C++

前端 未结 5 1388
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-04 18:41

I\'m trying to write a program in C++, which creates some files (.txt) and writes down the result in them. The problem is that an amount of these files is not fixed at the begin

相关标签:
5条回答
  • 2021-02-04 19:03

    You can get a const char* from an std::string by using the c_str member function.

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

    If you don't want to use std::string (maybe you don't want to do memory allocations) then you can use snprintf to create a formatted string:

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

    n here is the number in the filename.

    0 讨论(0)
  • 2021-02-04 19:07
     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
     }
    
    0 讨论(0)
  • 2021-02-04 19:07

    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 讨论(0)
  • 2021-02-04 19:14

    Sample code:

    #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 讨论(0)
  • 2021-02-04 19:15

    ... another way to bulid the filename

    #include <sstream>
    
    int n = 3;
    std::ostringstream os;
    os << "file_" << n << ".txt";
    
    std::string s = os.str();
    
    0 讨论(0)
提交回复
热议问题