- 论坛徽章:
- 0
|
我想在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
这个就得到了正确的输出。。。
不明白第一个为什么不行?
|
|