希望有人可以提供帮助。我正在解决某人在很久以前写过的“C代码”中的一个问题,并且此后他继续前进。
这段代码输出特定文件的时间戳。代码在Windows上运行时工作正常,但是当它在Linux上运行时,它会错误地显示Year。这一年没有在linux上显示,它显示35222.有没有人知道这里有什么问题?
由于
Windows输出:
Source file: test.dtl, Created: Mon, 27 May, 2013 at 16:13:20
Linux输出:
Source file: test.dtl, Created: Mon, 27 May, 35222 at 16:13:20
C代码中的函数:
void SummaryReport ( report_t *report, char *dtlName)
{
LogEntry(L"SummaryReport entry\n");
int i;
wchar_t *rootStrType,*localStr,timeStr[48];
wchar_t fileBuff[64];
struct tm *timeVals;
timeVals = localtime (&logHdr.date);
wcsftime (timeStr,47,L"%a, %#d %b, %Y at %X",timeVals);
/* Print the header information */
DisplayReportFile (report);
ReportEntry (report,L" Filesystem Audit Summary Report\n\n");
ReportEntry (report,L"Source file: %s, Created: %ls\n\n",dtlName,timeStr);
ReportEntry (report,L"Server: %ls",srvrName);
…
}
答案 0 :(得分:1)
验证了一个最小的例子,它“为我工作”。这是否显示正确的时间?
#include <wchar.h>
#include <time.h>
int main() {
wchar_t timeStr[48];
struct tm *timeVals;
time_t now = time(NULL);
timeVals = localtime(&now);
wcsftime(timeStr, 47, L"%a, %#d %b, %Y at %X", timeVals);
wprintf(timeStr);
return 0;
}
如果是,请检查文件本身 - 如果您正在共享文件系统,那么文件时间戳本身可能存在一些奇怪的问题? (或理解fs元数据)
答案 1 :(得分:1)
如果wcsftime()
本身呼叫localtime()
,请确保您的通话结果未被破坏。
struct tm timeVals;
timeVals = *localtime (&logHdr.date);
wcsftime (timeStr,47,L"%a, %#d %b, %Y at %X", &timeVals);
localtime()
将其结果保存在静态struct tm 某处。返回该位置的地址(指针)。对localtime()
或gmtime()
的后续调用会改变struct tm。我怀疑对wcsftime()
的调用是间接地在Linux中进行的。
BTW:localtime()可以返回NULL,因此更安全的代码会检查localtime()返回值。
您可能需要查看localtime_s()