当前时间作为创建文件的字符串

Current time as string for creating file

本文关键字:文件 字符串 创建 时间      更新时间:2023-10-16

所以这是我将当前名称的文件保存为文件名的函数。

cur_date = curDate(); 
cur_date.append(".txt");
myfile.open(cur_date.c_str(), std::ios::out | std::ios::app);
if (myfile.is_open()) 
{ 
    std::cout << message; 
    myfile << message; myfile << "n"; 
    answer.assign("OKn"); 
    myfile.close(); 
} else 
{ 
    std::cout << "Unable to open filen" << std::endl; 
    answer.assign("ERRn"); 
}

这是日期函数:

const std::string server_funcs::curDate() 
{ 
    time_t now = time(0); 
    struct tm tstruct; 
    char buf[80]; 
    tstruct = *localtime(&now);
    strftime(buf, sizeof(buf), "%Y-%m-%d_%X", &tstruct);
    return (const std::string)buf; 
}

我的问题是,open() 函数没有创建新文件,因此它转到 if 子句的 else 部分。但是当我使用不同的 char* 作为名称或静态输入时,它工作正常。所以我认为它与curDate()函数有关,但我不知道是什么...另外,如果我打印cur_date().c_str(),它显示正常。

函数 curDate() 返回一个字符串,形式为:"2013-10-15_19:09:02"。由于此字符串中有冒号,因此它不是允许的文件名。这就是打开函数失败的原因。

若要将冒号替换为点(例如),请更改为以下代码。此代码将指定另一种包含点而不是冒号的时间格式:

#include <algorithm>
const std::string server_funcs::curDate() 
{ 
    time_t now = time(0); 
    struct tm tstruct; 
    char buf[80]; 
    tstruct = *localtime(&now);
    strftime(buf, sizeof(buf), "%Y-%m-%d_%H.%M.%S", &tstruct);
    std::string result = buf;
    return result; 
}