fstream — передает системную дату и время как имя файла в переполнении стека

Я хотел создать систему посещаемости, которая бы использовала системную дату и время в качестве имени файла для ex:
это как обычно

int main () {
time_t t = time(0);   // get time now
struct tm * now = localtime( & t );
cout << (now->tm_year + 1900) << '-'
<< (now->tm_mon + 1) << '-'
<<  now->tm_mday
<< endl;
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}

но я хочу системную дату и время вместо example.txt
Я рассчитал время, включив заголовочный файл ctime в программу, приведенную выше. Это просто пример.

2

Решение

Ты можешь использовать strftime() функция форматирования времени в строку, он предоставляет гораздо больше возможностей форматирования в соответствии с вашими потребностями.

int main (int argc, char *argv[])
{
time_t t = time(0);   // get time now
struct tm * now = localtime( & t );

char buffer [80];
strftime (buffer,80,"%Y-%m-%d.",now);

std::ofstream myfile;
myfile.open (buffer);
if(myfile.is_open())
{
std::cout<<"Success"<<std::endl;
}

}
6

Другие решения

Вы можете попробовать использовать ostringstream для создания строки даты (как вы делаете с cout), а затем использовать ее str() функция-член для получения соответствующей строки даты.

0

Вы можете использовать класс stringstream для этой цели, например:

int main (int argc, char *argv[])
{
time_t t = time(0);   // get time now
struct tm * now = localtime( & t );
stringstream ss;

ss << (now->tm_year + 1900) << '-'
<< (now->tm_mon + 1) << '-'
<<  now->tm_mday
<< endl;

ofstream myfile;
myfile.open (ss.str());
myfile << "Writing this to a file.\n";
myfile.close();
return 0;

return(0);
}
0

#include <algorithm>
#include <iomanip>
#include <sstream>

std::string GetCurrentTimeForFileName()
{
auto time = std::time(nullptr);
std::stringstream ss;
ss << std::put_time(std::localtime(&time), "%F_%T"); // ISO 8601 without timezone information.
auto s = ss.str();
std::replace(s.begin(), s.end(), ':', '-');
return s;
}

замещать std::localtime* с std::gmtime* если вы работаете вместе за границей.

Использование, например:

#include <filesystem> // C++17
#include <fstream>
#include <string>

namespace fs = std::filesystem;

fs::path AppendTimeToFileName(const fs::path& fileName)
{
return fileName.stem().string() + "_" + GetCurrentTimeForFileName() + fileName.extension().string();
}

int main()
{
std::string fileName = "example.txt";
auto filePath = fs::temp_directory_path() / AppendTimeToFileName(fileName); // e.g. MyPrettyFile_2018-06-09_01-42-00.log
std::ofstream file(filePath, std::ios::app);
file << "Writing this to a file.\n";
}

*Увидеть Вот для потокобезопасной альтернативы этих функций.

0
По вопросам рекламы ammmcru@yandex.ru
Adblock
detector