使用readdir函数遍历
使用stat函数获得文件属性
1.头文件
#include <stdio.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
2.主函数
int main(int argc, const char *argv[])
{
DIR *dp;
struct dirent *dt;
struct stat buf;
int ret;
struct tm *t;
//以绝对寻址方式打开目录***
dp = opendir("/home/linux/wj_io");
if (dp == NULL){
perror("opendir");
return 0;
}
//遍历文件夹***
while((dt = readdir(dp)) != NULL){
printf("%s\n",dt->d_name);
//去除遍历时的'.'和'..'
if(*(dt->d_name) != '.'){
//读取文件的属性
ret = stat(dt->d_name,&buf);
if(ret < 0){
perror("stat");
return 0;
}
//打印文件大小
printf(" 文件大小:%7d ",(int)buf.st_size);
//打印文件时间
t = localtime(&buf.st_ctime);
printf(" 时间:%d-%d-%d %d:%d\n",t->tm_year+1900,
t->tm_mon+1,t->tm_mday,t->tm_hour,
t->tm_min);
}else{
puts("");在'.'和'..'后加一空行
}
}
return 0;
}
本文遍历的目录