Creating file names automatically C++

Tatiana picture Tatiana · Oct 28, 2012 · Viewed 23.9k times · Source

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 beginning and only appears near the end of the program. I would like to name these files as "file_1.txt", "file_2.txt", ..., "file_n.txt", where n is an integer.

I can't use concatenation because the file name requires type "const char*", and I didn't find any way to convert "string" to this type. I haven't found any answer through the Internet and shall be really happy if you help me.

Answer

Peter Alexander picture Peter Alexander · Oct 28, 2012

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.