C++ 当前时间作为创建文件的字符串
这是我的功能,用当前名称将文件保存为文件名C++ 当前时间作为创建文件的字符串,c++,date,C++,Date,这是我的功能,用当前名称将文件保存为文件名 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"; an
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("OK\n");
myfile.close();
} else
{
std::cout << "Unable to open file\n" << std::endl;
answer.assign("ERR\n");
}
我的问题是,open()函数没有创建新文件,因此它转到if子句的else部分。。
但是当我使用不同的char*作为名称或静态输入时,效果很好。
所以我猜测它与curDate()函数有关,但我不知道。。。另外,如果我打印cur_date().c_str(),它将显示fine..函数curDate()以“2013-10-15_19:09:02”的形式返回字符串。
因为此字符串中有冒号,所以它不是允许的文件名。这就是open函数失败的原因
要将冒号替换为点(例如),请更改为以下代码。
此代码将指定另一种包含点而不是冒号的时间格式:
#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;
}
#包括
const std::string server_funcs::curDate()
{
现在时间=时间(0);
struct-tm-tstruct;
char-buf[80];
tstruct=*本地时间(&now);
strftime(buf,sizeof(buf),%Y-%m-%d.%H.%m.%S“,&t结构);
std::string result=buf;
返回结果;
}
为什么server\u funcs::curDate()
返回const std::string
?属于什么类型的id当前日期?请给我们一个可编译的代码。。
#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;
}