自动生成文件名 C++

5
我正在尝试用C++编写一个程序,它会创建一些文件(.txt),并将结果写入这些文件中。问题是,在程序开始时,这些文件的数量是不确定的,只有在程序末尾才会出现。我想把这些文件命名为"file_1.txt"、"file_2.txt"、......、"file_n.txt",其中n是一个整数。
我不能使用字符串连接,因为文件名需要类型为"const char*",而我没有找到任何将"string"转换为此类型的方法。我在互联网上也没有找到任何答案,如果您能帮助我,我将非常高兴。

你看过 c_str 函数吗?http://en.cppreference.com/w/cpp/string/basic_string/c_str - R. Martinho Fernandes
仅仅因为最终文件名需要是 const char* 类型,并不意味着你的整个程序都必须使用它。你应该尽可能多地使用 std::string,只有在真正需要时才从中获取 const char* - Lightness Races in Orbit
5个回答

7

使用c_str成员函数可以从std::string获取一个const char*

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指的是文件名中的数字。


关于 std::string 的内存分配说明:许多实现都会进行小字符串优化,其中小字符串不会分配内存,但这并不是保证。 - Peter Alexander
@PeterAlexander:嗯,MSVC的dirkumware版本具有SSO,而gcc的libstdc++没有。我认为clang的libc++也具有SSO,但由于它在OS X之外的移植很少,所以对大多数人来说没有什么兴趣。 - Matthieu M.

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

3

另一种构建文件名的方法

#include <sstream>

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

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

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

1
我使用以下代码实现此功能,您可能会发现这很有用。
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();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接