Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/139.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 当前时间作为创建文件的字符串_C++_Date - Fatal编程技术网

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; 
}