c++不能在当前系统时间和日期之后命名txt文件
C++ cannot name txt file after current sytem time and date
我对这个代码有问题。它会编译,但是一旦我在程序中按回车键,它就会说:
Unhandled exception at 0x008E8641 in Log Test.exe: 0xC0000005: Access violation reading location 0x566D846A.
代码如下:
#include <iostream>
#include <time.h>
#include <fstream>
using namespace std;
int main() {
cin.get();
time_t Time;
Time = time(0);
string Date = __DATE__;
string LOG = Time + "_" + Date;
ofstream TEST;
TEST.open(LOG);
TEST << "This Text Should Appear Inside Of File.";
TEST.close();
cout << "Log has been Made.";
cin.get();
return 0;
}
我认为问题是时间和如何我试图把它放入一个字符串,但我不知道我做了什么不工作。
我认为Time
是一个整数类型,所以如下:
Time + "_"
会导致指针的添加,因此添加到字符串上的是指向"_"
开头以外的某个位置的坏指针。
您可以看到像"_"
这样的字符串字面值实际上解析为地址(指针)。给它添加一个像Time
这样的整数可以使它指向内存中的其他地方。
首先,您需要将Time
转换为字符串。
我碰巧有这段代码,可能对你有用:
std::string get_stamp()
{
time_t t = std::time(0);
char buf[sizeof("YYYY-MM-DD HH-MM-SS")];
return {buf, std::strftime(buf, sizeof(buf), "%F %H-%M-%S", std::localtime(&t))};
}
注意:使用std::localtime
不是威胁安全的
如果您启用了编译器警告,它应该会向您发出警告:
string LOG = Time + "_" + Date;
这里,Time
被转换为指针,你得到未定义的行为。对于一个不完全的c++解决方案,我推荐这个简单的方法:
time_t t = time(0);
struct tm ttm;
localtime_r( &t, &ttm );
char timestamp[20]; // actually only need 17 chars plus terminator.
sprintf_s( timestamp, sizeof(timestamp), "%04d-%02d-%02d_%02d%02d%02d",
ttm.tm_year + 1900, ttm.tm_mon + 1, ttm.tm_day, ttm.tm_hour, ttm.tm_min, ttm.tm_sec );
string logfilename = string(timestamp) + ".log";
ofstream logfile( logfilename.c_str() );
注意localtime_r
不是完全可移植的。在windows上,使用localtime_s
,不幸的是它也颠倒了参数的顺序。
相关文章:
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 查询SQLite数据库中的日期
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 在类定义之后定义一个私有方法
- 在循环C++中指定字符串之后,不会打印该字符串
- C++宏忽略之后的内容
- 要与"if constexpr"一起使用的编译时消息(在预处理器之后)
- Log4cpp:以UTC/GMT时区打印日期
- 使用C++的日期库读取时间
- strncpy之后的char数组的错误行为
- 计算十进制 c++ 之后的数字
- 日期格式为C++
- "x += x--"之后的 x 是什么?
- 类的前向声明之后的类成员函数定义,在类声明之前
- 如何在 C++20 计时中为日期添加天数?
- 为什么将双精度转换为 int 似乎在第 16 位数字之后将其四舍五入?
- 如何在QTableView中排序和更改日期格式
- 如何在cpp中使用地图显示给定日期范围内(在下面的问题中)的费率?
- 如何在当前日期/时间之后命名我创建的文本文件
- c++不能在当前系统时间和日期之后命名txt文件