【问题标题】:ctime_r on MSVCMSVC 上的 ctime_r
【发布时间】:2016-03-02 15:07:05
【问题描述】:

我有这个功能,如果我使用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();
}

【问题讨论】:

  • 本人不熟悉POSIX,不太清楚ctime_r是做什么的,但从签名来看,相当于ctime_s and its friends

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


【解决方案1】:

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

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
}

【讨论】:

    猜你喜欢
    • 2019-02-06
    • 2013-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-22
    • 1970-01-01
    相关资源
    最近更新 更多