Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating file names automatically C++

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.

like image 314
Tatiana Avatar asked Oct 28 '12 12:10

Tatiana


People also ask

How do you name a file in C programming?

To rename a file in C, use rename() function of stdio. h. rename() function takes the existing file name and new file names as arguments and renames the file. rename() returns 0 if the file is renamed successfully, else it returns a non-zero value.

How to change file name dynamically in c#?

The code line where you assign the file name you need to everytime create a unique name so the previous one does not get overwritten, the best was is using GUID in the file name. So string fileName = @"c:\samplereport. pdf"; should be something like.

Can Windows file names have commas?

doc” where?. This alteration can cause confusion in identifying the actual file name. Punctuation, symbols, or special characters (periods, commas, parentheses, ampersands, asterisks, etc.) should be avoided.

Can File names have multiple periods?

Theory. Since long filenames and VFAT exist, filenames with two periods in them are perfectly valid in Windows. As far as the modern file system is concerned, there's no such thing as an extension. A period is a character like any else.


1 Answers

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.

like image 171
Peter Alexander Avatar answered Sep 30 '22 15:09

Peter Alexander