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

Chi*_*kar 2 c++ fstream ctime

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

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;
} 
Run Code Online (Sandbox Code Playgroud)

但我希望系统日期和时间代替example.txt我通过在上面的程序中包含ctime头文件来计算时间只是示例.

Sin*_*ngh 6

您可以使用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;
      }

}
Run Code Online (Sandbox Code Playgroud)