I am trying to create a file from C++ code with format(name + UTC Date Time) using std::fstream, but every time it is showing that it cannot create a file that I am printing using std::cout. No idea why this is happening.
Below is the code which is printing the output:
void IOfile::writeCsv(string write_file) {
write_file.erase(std::remove_if(write_file.begin(), write_file.end(), ::isspace), write_file.end());
cout << write_file.size() << endl;
cout << write_file << endl;
string placeholder = ".csv";
string finalFile = write_file + placeholder;
cout << finalFile.size()<<endl;
cout << finalFile<< endl;
fstream file;
file.open(finalFile, fstream::out);
if (!file)
{
cout << "Error in creating file!!!";
}
else {
cout << "File created successfully.";
}
file.close();
}
Place where the writeCSV() function is getting called. Data in below code is object of the class which contains the writeCSV function:
string dateTime = data.getDateTime();
string fileName = "Big" + dateTime;
Above code is calling one function getDateTime() which is returning the current GMT time.
string IOfile::getDateTime()
{
time_t now = time(0);
char* currentTime = ctime(&now);
tm* gmtm = gmtime(&now);//to get GMT time
currentTime = asctime(gmtm);
return currentTime;
};
Output which I am getting:
23
BigMonApr2422:45:572023
27
BigMonApr2422:45:572023.csv
Error in creating file!!!
On many systems, you can't use
:in a file name. For example, on Windows:Naming Files, Paths, and Namespace
Also see this question: Allowed characters in filename
So, you need to change the
:characters to something more acceptable, like-or_, or just eliminate them completely.Also, consider using functions that give you control over the formatting of your file name, so that you can include only what you actually want rather than removing what you don't want.
For example, using
std::strftime():Or, using
std:::put_time:Or, using
std::format():Just on a side note: a file name like
BigMonApr2422:45:572023.csvis a little hard to read/understand, especially the2422and572023portions. Consider using more readable file names, for example:Big_YYYY-MM-DD_HH-MM-SS.csvlikeBig_2023-04-24_22-45-57.csv