c++不能在当前系统时间和日期之后命名txt文件

C++ cannot name txt file after current sytem time and date

本文关键字:之后 日期 文件 txt 时间 不能 系统 c++      更新时间:2023-10-16

我对这个代码有问题。它会编译,但是一旦我在程序中按回车键,它就会说:

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,不幸的是它也颠倒了参数的顺序。