在c++中传递系统日期和时间作为文件名
Pass system date and time as a filename in C++
我想做一个考勤系统,它将系统日期和时间作为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头文件来计算时间,上面的程序只是示例。
您可以使用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;
}
myfile.close();
return 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";
}
您可以尝试使用ostringstream来创建日期字符串(就像您使用cout一样),然后使用它的str()
成员函数来检索相应的日期字符串。
您可以使用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);
}
相关文章:
- C++为构建时间获取QDateTime的可靠方法
- 从命令行c++发送文本文件名
- 从持续时间构造std::chrono::system_clock::time_point
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- while循环中while循环的时间复杂度是多少
- 使用简单类型列表实现的指数编译时间.为什么
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 在已经使用Git的情况下减少编译时间
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 在 C++ 中为文件名添加时间戳
- 如何在C 中读取具有前缀和时间戳为文件名的文件
- 无法创建包含日期和时间的文件名(C++)
- 将文件名的文件另存为当前时间日期
- 文件名为自c++中的epoch以来的当前时间(以秒为单位)
- 日志文件名中的 Pantheios 日期/时间
- 具有文件名、行和时间戳的日志记录器
- 获取时间作为文件名
- 如何在C++中保存带有日期和时间的图像文件名?
- 在c++中传递系统日期和时间作为文件名