MSVC上的ctime_r

时间:2016-03-02 15:07:05

标签: c++ visual-studio-2010 visual-c++

我有这个功能,如果我使用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] = '\0'; // remove the ending \n
    } else {
        current_date_string[0] = '\0'; // 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();
}

1 个答案:

答案 0 :(得分:3)

在MS库中,有一个ctime_s,它允许ctime_r在Linux / Unix OS中具有相同的“不使用全局”功能。您可能需要像这样包装它:

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
}