【问题标题】:strftime not giving correct output with %C option - Solaris 10strftime 没有使用 %C 选项给出正确的输出 - Solaris 10
【发布时间】:2013-06-28 18:55:30
【问题描述】:

我们在配置文件中使用 /usr/xpg4/bin 作为默认路径。 我们在这里打印变量“curr_date”的输出:

   lt = time(NULL);
   ltime=localtime(localtime(&lt));
   strftime(curr_date,sizeof(curr_date),"%m/%d/%y%C",ltime);

我们得到的输出是“06/27/13Thu Jun 27 02:39:34 PDT”而不是“06/27/1320”。

你知道在这里应该使用什么格式说明符吗?

谢谢

【问题讨论】:

  • 在命令行输入man strftime
  • man 说:符合标准的 %C 世纪数(年份除以 100 并截断为十进制数 [01,99] 的整数)。这是 Solaris 2.4 到 Solaris 10 首次支持的标准的符合标准的行为。
  • 但是 %C 没有得到“20”,而是得到“Thu Jun 27 02:39:34 PDT”

标签: c solaris strftime


【解决方案1】:

在 $PATH 中使用 /usr/xpg4/bin 只会选择符合标准的命令,它不会更改程序中的函数调用以使用符合标准的版本。

Solaris standards(5) man page 中所述,您需要使用各种#defines 和编译器标志来指定各种标准的合规性。

例如,获取您的代码 sn-p 并将其扩展为这个独立的测试程序:

#include <sys/types.h>
#include <time.h>
#include <stdio.h>

int main(int argc, char **argv)
{
    time_t lt;
    struct tm *ltime;
    char curr_date[80];

    lt = time(NULL);
    ltime = localtime(&lt);
    strftime(curr_date, sizeof(curr_date), "%m/%d/%y%C", ltime); 
    printf("%s\n", curr_date);
    return 0;
}

然后用不同的标志编译显示不同的行为:

% cc -o /tmp/strftime /tmp/strftime.c
% /tmp/strftime
06/30/13Sun Jun 30 20:28:00 PDT 2013

% cc -xc99 -D_XOPEN_SOURCE=600 -o /tmp/strftime /tmp/strftime.c
% /tmp/strftime
06/30/1320

默认模式向后兼容传统的 Solaris 代码,第二种形式要求符合 C99 和 XPG6 (Unix03) 标准。

【讨论】:

  • 感谢阿兰克!这有帮助。
【解决方案2】:

仔细查看调用strftime() 和打印curr_date 之间的代码。您正在某处覆盖curr_data,因为您打印的开头是正确的。 curr_data 的内存管理也可能有问题;怎么定义的,你给curr_data分配内存了吗?

strftime() 之后设置一个断点,您会看到它包含预期/正确的字符串。

【讨论】:

  • 嗨..我们看到相同的代码在 HP-UX 等其他操作系统上运行,但在 Solaris 上失败。我们的猜测可能是它在内部使用了与 /usr/bin/date 功能类似的东西,而不是 /usr/xpg4/bin。但不确定是否有针对这种情况的替代方案。 > /usr/bin/date +%C Fri Jun 28 13:31:23 PDT 2013 > /usr/xpg4/bin/date +%C 20
猜你喜欢
  • 2018-09-13
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-24
  • 1970-01-01
  • 2022-06-10
相关资源
最近更新 更多