LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 1064|回复: 4

如何将ctime的返回值赋到数组去。

[复制链接]
发表于 2003-10-1 14:19:51 | 显示全部楼层 |阅读模式
比如:我想得到最后修改时间,ctime(&buf.st_atime),buf是struct stat的类型。我想要将上面的函数的返回值存在一个数组中,该怎么做呢?
ctime返回的是一个静态的指针,我写
  1. char t[100];
  2.       t = ctime(&buf.st_atime);
  3.       printf("%s", t);
复制代码

为什么不对?
发表于 2003-10-1 14:48:17 | 显示全部楼层

  1. include <stdio.h>
  2. #include <time.h>

  3. int main()
  4. {
  5.         char localTime[100];
  6.         const time_t *timep;
  7.         
  8.         sprintf(localTime, ctime(timep));

  9.         printf("%s", localTime);
  10.         
  11.         return 0;
  12. }
复制代码


这个是获取本地时间。参考一下。

  1. #include <stdio.h>
  2. #include <time.h>

  3. int main()
  4. {
  5.         char localTime[100];
  6.         const time_t *timep;

  7.         ctime_r(timep, localTime);

  8.         printf("%s", localTime);

  9.         return 0;
  10. }
复制代码

更简单。

发表于 2003-10-1 15:49:47 | 显示全部楼层

  1. #include <stdio.h>
  2. #include <sys/types.h>
  3. #include <unistd.h>
  4. #include <sys/stat.h>
  5. #include <time.h>

  6. int main()
  7. {
  8.         char t[100];
  9.         struct stat buf;
  10.         int s;
  11.         s = stat("test.txt", &buf);
  12.         if (s == -1)    return -1;

  13.         const time_t *bufp = &buf.st_atime;     
  14.         // 这里很重要,必须传递一个指向常量对象的指针。
  15.         
  16.         ctime_r (bufp, t);
  17.         printf ("%s", t);

  18.         return 0;
  19. }
复制代码
发表于 2003-10-1 15:52:34 | 显示全部楼层
纠正一句, const time_t *timep 不是静态指针,静态用 static 来标识,完全是两个概念。
 楼主| 发表于 2003-10-1 16:08:07 | 显示全部楼层
谢谢,您帮了大忙了。
讲得很详细!
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表