自动创建文件名C ++

时间:2012-10-28 12:58:55

标签: c++ file names const-char

我正在尝试用C ++编写一个程序,它创建一些文件(.txt)并将结果写入其中。问题是这些文件的数量在开始时没有固定,只出现在程序结束附近。我想将这些文件命名为“file_1.txt”,“file_2.txt”,...,“file_n.txt”,其中n是整数。

我不能使用连接,因为文件名需要类型“const char *”,我没有找到任何方法将“string”转换为此类型。我没有通过互联网找到任何答案,如果你帮助我,我会非常高兴。

5 个答案:

答案 0 :(得分:6)

您可以使用c_str会员功能从const char*获得std::string

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

如果您不想使用std::string(也许您不想进行内存分配),那么您可以使用snprintf创建格式化字符串:

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

n这是文件名中的数字。

答案 1 :(得分:5)

 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
 }

答案 2 :(得分:1)

......构建文件名的另一种方法

#include <sstream>

int n = 3;
std::ostringstream os;
os << "file_" << n << ".txt";

std::string s = os.str();

答案 3 :(得分:1)

示例代码:

#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;
}

答案 4 :(得分:0)

我使用以下代码,您可能会觉得这很有用。

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();
相关问题