2012-10-28 39 views
4

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

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

+0

你看过'c_str'函数吗? http://en.cppreference.com/w/cpp/string/basic_string/c_str –

+0

仅仅因为文件名最终需要是一个“const char *”,并不意味着你在整个程序中一直使用它。你应该尽可能地使用'std :: string',然后只有当你真的这样才能从中获得'const char *'。 –

回答

5

通过使用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这里是编号在文件名中。

+0

关于'std :: string'内存分配的说明:很多实现都是在小字符串不会分配内存的情况下进行小字符串优化,但是这并不能保证。 –

+0

非常感谢!:) – Tatiana

+0

@PeterAlexander:嗯,MSVC的dirkumware版本有SSO,而gcc的libstdC++没有。我认为clang的libC++也有SSO,但是因为它几乎没有移植到OS X之外,所以它对大多数人来说都没什么兴趣。 –

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

...另一种方式来bulid文件名

#include <sstream> 

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

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

示例代码:

#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

我用这个下面的代码,你可能会发现这很有用。

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();