【问题标题】:year not displaying on linux年份不显示在 linux 上
【发布时间】:2023-03-10 23:02:01
【问题描述】:

希望有人可以提供帮助。我正在修复某人很久以前编写的 C 代码中的一个问题,而他后来继续前进。

这段代码输出特定文件的时间戳。该代码在 Windows 上运行时运行良好,但在 Linux 上运行时显示年份不正确。 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);
…
}

【问题讨论】:

  • Linux 系统上的日期——特别是年份——设置是否正确?
  • Linux 比 Windows 先进得多。
  • 我猜,这是由于 Windows 和 Unix 使用不同的时基。 Unix 从 1.1.1970 开始计算秒数 - 我不知道 Windows 做了什么,但我敢打赌不同的东西......
  • logHdr.date 来自哪里?
  • 尝试打印出 timeVals->tm_year 以确保您的 tm 值正确。

标签: c linux unix


【解决方案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 元数据)

【讨论】:

    【解决方案2】:

    如果wcsftime() 自己调用localtime(),请确保您的调用结果没有损坏。

    struct tm timeVals;
    timeVals = *localtime (&logHdr.date);
    wcsftime (timeStr,47,L"%a, %#d %b, %Y at %X", &timeVals);
    

    localtime() 将其结果保存在静态结构 tm somewhere 中。返回指向该位置的地址(指针)。随后对localtime()gmtime() 的调用会改变结构tm。我怀疑对 wcsftime() 的调用在 Linux 中间接地这样做了。

    顺便说一句:localtime() 可能返回 NULL,因此更安全的代码会检查 localtime() 返回值。

    您可能想查看localtime_s()

    【讨论】:

      猜你喜欢
      • 2015-10-30
      • 2016-01-26
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-04
      相关资源
      最近更新 更多