ctime_r 在 MSVC 上

ctime_r on MSVC

我有这个功能,如果我使用g++,它会编译得很好。问题是我必须使用 windows 编译器,但它没有 ctime_r。我对 C/C++ 有点陌生。谁能帮我用 MSVC cl.exe 完成这项工作?

函数:

void leaveWorld(const WorldDescription& desc)
{
    std::ostringstream os;
    const time_t current_date(time(0));
    char current_date_string[27];
    const size_t n = strlen(ctime_r(&current_date,current_date_string));
    if (n) {
        current_date_string[n-1] = '[=11=]'; // remove the ending \n
    } else {
        current_date_string[0] = '[=11=]'; // just in case...
    }
    os << totaltime;
    (*_o) << "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" << endl;
    (*_o) << "<testsuite name=\"" << desc.worldName() << "\" ";
    (*_o) << "date=\"" << current_date_string;
    (*_o) << "\" tests=\"" << ntests
          << "\" errors=\"" << nerror
          << "\" failures=\"" << nfail
          << "\" time=\"" << os.str().c_str() << "\" >";
    _o->endl(*_o);
    (*_o) << _os->str().c_str();
    _os->clear();
    (*_o) << "</testsuite>" << endl;
    _o->flush();
}

在 MS 库中,有一个 ctime_s,它允许与 ctime_r 在 Linux/Unix OS 中具有相同的 "not using a global" 功能。您可能必须像这样包装它:

const char *my_ctime_r(char *buffer, size_t bufsize, time_t cur_time)
{
#if WINDOWS
    errno_t e = ctime_s(buffer, bufsize, cur_time);
    assert(e == 0 && "Huh? ctime_s returned an error");
    return buffer;
#else 
    const char *res = ctime_r(buffer, cur_time);
    assert(res != NULL && "ctime_r failed...");
    return res;
#endif
}