首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在C++中将系统日期和时间作为文件名传递

在C++中将系统日期和时间作为文件名传递
EN

Stack Overflow用户
提问于 2014-03-11 14:49:28
回答 4查看 19.6K关注 0票数 3

我想做一个考勤系统,它将系统日期和时间作为文件的文件名,例如:这是它通常是这样的

代码语言:javascript
复制
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头文件来计算时间,这只是个例子。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2014-03-11 15:34:30

你可以使用strftime()函数将时间格式化成字符串,它根据你的需要提供了更多的格式化选项。

代码语言:javascript
复制
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;
}
票数 10
EN

Stack Overflow用户

发布于 2018-06-19 03:18:11

代码语言:javascript
复制
#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*。

用法例如:

代码语言:javascript
复制
#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";
}

*有关这些函数的线程安全替代方案,请参阅here

票数 2
EN

Stack Overflow用户

发布于 2014-03-11 14:55:03

您可以尝试使用ostringstream来创建日期字符串(就像使用cout所做的那样),然后使用它的str()成员函数来检索相应的日期字符串。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22318389

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档