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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With