免费注册 查看新帖 |

Chinaunix

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

linux 下得不到目录文件的正确时间 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2012-07-02 21:42 |只看该作者 |倒序浏览
我想在linux读取目录文件时间,结果得出的结果跟时间文件修改时间不一样,很是不解。。。请各位大侠赐教,附上源代码

C/C++ code
#include <dirent.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

void deal_file(struct stat statbuf)
{
    char strTime[20]="";
    printf("m_time=%ld\n",statbuf.st_mtime);
    strftime(strTime,sizeof(strTime),"%Y%m%d%H%M", localtime(&statbuf.st_mtime));
    printf("time=%s\n",strTime);
}

void list(char *dir_name)
{
    DIR *dp;
    struct dirent *entry;
    struct stat statbuf;
    if((dp=opendir(dir_name))==NULL)
    {
        printf("Open dir error.\n");
    }
    else
    {
        while((entry=readdir(dp))!=NULL)
        {
            lstat(entry->d_name,&statbuf);
            printf("file=%s,time=%ld\n",entry->d_name,statbuf.st_mtime);
            if(S_ISDIR(statbuf.st_mode))
            {
                if((strcmp(entry->d_name,".")!=0)&&(strcmp(entry->d_name,"..")!=0))
                {
                    printf("dir=%s\n",entry->d_name);
                }
            }
            else
            {
                deal_file(statbuf);
            }
        }
    }
}


int main(int argc,char *argv[])
{
    list(argv[1]);
    return 0;
}


输出结果:
#./ergodic_2 /home/test/temp/
m_time=1335336656
time=201204251450

ls -l的结果:
# ls -l /home/test/temp/
total 0
-rw-r--r-- 1 root root 0 2012-07-02 17:30 test_file


后来又写了个简单的测试小程序:

C/C++ code
#include <dirent.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

void list(char *dir_name)
{
        DIR *dp;
        struct dirent *entry;
        struct stat statbuf;
        char strTime[20]="";
        lstat(dir_name,&statbuf);
        strftime(strTime,sizeof(strTime),"%Y%m%d%H%M", localtime(&statbuf.st_mtime));
        printf("time=%s\n",strTime);
}

int main(int argc,char *argv[])
{
        list(argv[1]);
        return 0;
}


输出结果:
# ./ergodic_order /home/test/temp/test_file
time=201207021730
这个就得到了正确的输出。。。


不明白第一个为什么不行?

论坛徽章:
0
2 [报告]
发表于 2012-07-03 20:18 |只看该作者
工作路径问题,加入chdir即可,结贴
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP