当前时间作为创建文件的字符串
Current time as string for creating file
所以这是我将当前名称的文件保存为文件名的函数。
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;
}
相关文章:
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 有没有办法从非C/C++文件中读取C++原始字符串文字的内容
- 如何打开并写入一个名称取自C++中字符串的文件
- 如何从二进制文件中读取字符串
- 如何在 c++ 中使用 getline 从文件中读取字符串?
- 将字符串与文件上的数据进行比较
- 用户输入字符串的文件附加问题..C++
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- 如何使字符串出现在编译的二进制可执行文件的开头?
- 使用文件内容作为硬编码字符串
- 将文件复制到自定义位置,存在字符串转换问题
- 在 c++ 中连接字符串和整数,以便在 C++ 11 不支持计算机的情况下读取多个文件
- 声明要在 qml 和 cpp 文件中使用的全局字符串
- C 通过char读取文件字符串的文件char;崩溃
- 我不明白如何将 toupper 和 isalpha 与.txt文件字符串输入一起使用
- 在 CPP 文件中使用 make 文件字符串变量
- 编译 PyGAMMA Mac Lion:g++ 找不到标准的 C++ 头文件(字符串/iostream..)
- 如何在c++中使用文件字符串作为命令
- 使用 TinyXML 解析 XML 文件字符串
- 递归下降解析器帮助(不读取文本文件字符串)