使用ctime进行分段故障

时间:2012-09-09 12:10:53

标签: c gcc segmentation-fault

我正在进行stat() - 调用,返回一个包含我想要提取的信息的结构。到目前为止,我成功地获得了我想要的东西,直到获得访问,修改和上次更改文件的时间。

我想使用ctime来获取它,然后使用printf将其打印出来。

    printf("File: %s",argv[1]);
    printf("\nSize: %d",result.st_size);
    printf("        Blocks: %d",result.st_blocks);
    printf("        IO Block: %d",result.st_blksize);
    printf("\nDevice: 0x%x",result.st_dev);
    printf("        Inode: %d",result.st_ino);
    printf("        Links: %d",result.st_nlink);
//  printf("\nAccess: %s",ctime(result.st_atime));

此代码运行良好,并提供以下输出:

File: /etc/passwd
Size: 2250043           Blocks: 4416            IO Block: 4096
Device: 0x6804          Inode: 9738432          Links: 1

如果我取消注释我想要获取访问时间的最后一行,我会得到此输出:

File: /etc/passwd
Size: 2250043           Blocks: 4416            IO Block: 4096
Segmentation fault

我该如何解决这个问题?另外,为什么我在设备之前得到分段错误,Inode和链接被打印出来了?不应该打印然后生成分段错误吗?

我对C的经验很少。我在之前的课程中学习过Assembly,但非常简短。我试图阅读time.h的API,但我无法真正找到解决方案。

我非常感谢能得到的任何帮助或提示!

谢谢, ž

2 个答案:

答案 0 :(得分:3)

函数ctime需要const time_t *。你可能想要:

printf("\nAccess: %s",ctime(&result.st_atime));
                            ^

答案 1 :(得分:3)

请使用

ctime(&result.st_atime)

并且不要忘记

#include <time.h>