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

时间:2013-10-15 16:50:56

标签: 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"; 
    answer.assign("OK\n"); 
    myfile.close(); 
} else 
{ 
    std::cout << "Unable to open file\n" << std::endl; 
    answer.assign("ERR\n"); 
}

这是日期函数:

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()它显示正常..

1 个答案:

答案 0 :(得分:2)

函数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; 
}
相关问题