ctime_r

问题描述 投票:0回答:2

我有这个函数,如果我使用

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();
}
c++ visual-studio-2010 visual-c++
2个回答
2
投票

在 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
}

0
投票

我更喜欢宏,因此您可以在两个平台上使用相同的代码。

#if defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
#  define ctime_r(t, b) ctime_s(b, sizeof(b), t)
#endif /* _WIN32 || _WIN64 || __CYGWIN__ */

如果你关心返回值,从两个函数的签名来看:

char *ctime_r(const time_t *timep, char *buf);
errno_t ctime_s(char* buffer, size_t numberOfElements, const time_t *sourceTime);

你可以这样写:

#if defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
#  define my_ctime_r(t, b) (0 == ctime_s(b, sizeof(b), t))
#else
#  define my_ctime_r(t, b) (NULL != ctime_s(b, sizeof(b), t))
#endif /* !_WIN32 && !_WIN64 && !__CYGWIN__ */

这样会统一

my_ctime_r()
的返回值,成功则返回1,失败则返回0。

© www.soinside.com 2019 - 2024. All rights reserved.