Creating file names automatically C++

前端 未结 5 1442
佛祖请我去吃肉
佛祖请我去吃肉 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: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();
    

提交回复
热议问题