免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
12下一页
最近访问板块 发新帖
查看: 8095 | 回复: 10
打印 上一主题 下一主题

[C] 求助!!LINUX中关于struct stat 和 ctime函数?? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-03-11 12:55 |只看该作者 |倒序浏览
从struct stat中获取file的 time of last access,并用char *ctime(time_t *t)转换成可读形式

以下是我写的一段程序,程序编译正常通过,当运行时返回:Segmentation fault

请问是怎么回事,谢谢了。

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>

int main(int args,char *argv[]){
            
             struct stat * statbuf;
             if(args < 2){
                    printf("please input a file\n");
                    exit(1);
              }

             if(stat(argv[1],statbuf) == 0){
                       time_t t = statbuf->st_atime;
                       printf("%s\n",ctime(&t));

              }
             else{
                     perror(argv[1]);
                     exit(1);
              }

              return 0;
}

论坛徽章:
0
2 [报告]
发表于 2008-03-11 13:18 |只看该作者
struct stat statbuf;


stat(argv[1], &statbuf)

论坛徽章:
0
3 [报告]
发表于 2008-03-11 13:24 |只看该作者

回复 #2 yjm0573 的帖子

恩,这样确实能达到目的。
但你知道对 struct stat 用指针 错在哪里么?

论坛徽章:
0
4 [报告]
发表于 2008-03-11 13:39 |只看该作者
原帖由 xuwlhhui 于 2008-3-11 13:24 发表
恩,这样确实能达到目的。
但你知道对 struct stat 用指针 错在哪里么?

复习一下C语言的基础知识吧

论坛徽章:
0
5 [报告]
发表于 2008-03-11 14:24 |只看该作者

回复 #4 G00GLE 的帖子

呵呵,谢谢建议,我刚学C语言和LINUX编程。
有哪位知道么,帮帮忙撒

论坛徽章:
0
6 [报告]
发表于 2008-03-11 14:41 |只看该作者
这个指针你分配内存了吗?至少你也应该new块内存吧?

论坛徽章:
0
7 [报告]
发表于 2008-03-11 14:49 |只看该作者
原帖由 xuwlhhui 于 2008-3-11 14:24 发表
呵呵,谢谢建议,我刚学C语言和LINUX编程。
有哪位知道么,帮帮忙撒

除了2楼的方法,如果你要用指针的话,可以这样

struct stat * statbuf;
statbuf = (struct stat *)malloc(sizeof(struct stat));

下面的和你原代码相同。

论坛徽章:
0
8 [报告]
发表于 2008-03-11 14:52 |只看该作者

回复 #7 G00GLE 的帖子

谢谢指导

论坛徽章:
0
9 [报告]
发表于 2008-03-11 16:11 |只看该作者
看看man帮助

man stat
"stat stats the file pointed to by file_name and fills in buf."

看清上面这句话了吗? 是fills in,不是pointed by。

论坛徽章:
0
10 [报告]
发表于 2008-03-11 16:11 |只看该作者
原帖由 G00GLE 于 2008-3-11 14:49 发表

除了2楼的方法,如果你要用指针的话,可以这样

struct stat * statbuf;
statbuf = (struct stat *)malloc(sizeof(struct stat));

下面的和你原代码相同。



用完了记得要free一下
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP