一、目录读取
opendir函数用来打开一个目录文件:
#include <dirent.h>
DIR *opendir(const char *name);
DIR *fdopendir(int fd); 使用文件描述符,要配合open函数使用
DIR是用来描述一个打开的目录文件的结构体类型
成功时返回目录流指针;出错时返回NULL
readdir函数用来读取目录流中的内容:
#include <dirent.h>
struct dirent *readdir(DIR *dirp);
struct dirent是用来描述目录流中一个目录项的结构体类型
包含成员char d_name[256] 参考帮助文档
成功时返回目录流dirp中下一个目录项;
出错或到末尾时时返回NULL
closedir函数用来关闭一个目录文件:
#include <dirent.h>
int closedir(DIR *dirp);
成功时返回0;出错时
#include <dirent.h>
#include <stdio.h>
int main(int argc,char **argv){
DIR* dp;
struct dirent *dt;
dp=opendir("/mnt/hgfs/share/newIOP/");
if(dp == NULL){
perror("opendir");
return 0;
}
while((dt=readdir(dp))!=NULL){
printf("%s\n",dt->d_name);
}
closedir(dp);
}
返回EOF
二、文件属性获取
chmod/fchmod函数用来修改文件的访问权限:
#include <sys/stat.h>
int chmod(const char *path, mode_t mode);
int fchmod(int fd, mode_t mode);
成功时返回0;出错时返回EOF
root和文件所有者能修改文件的访问权限
示例: chmod(“test.txt”, 0666);
#include <stdio.h>
#include <sys/stat.h>
int main(int argc,char **argv){
int ret;
ret = chmod("temp",0444);
if(ret<0){
perror("chmod");
return 0;
}
}
stat/lstat/fstat函数用来获取文件属性:
#include <sys/stat.h>
int stat(const char *path, struct stat *buf);
int lstat(const char *path, struct stat *buf);
int fstat(int fd, struct stat *buf);
成功时返回0;出错时返回EOF
如果path是符号链接stat获取的是目标文件的属性;而lstat获取的是链接文件的属性
struct stat是存放文件属性的结构体类型:
mode_t st_mode 类型和访问权限;
uid_t st_uid 所有者id;
uid_t st_gid 用户组id;
off_t st_size 文件大小;
time_t st_mtime 最后修改时间;
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
int main (int argc,char **argv){
struct stat buf;
int ret;
ret = stat("chmod_t.c",&buf);
if(ret<0){
perror("stat");
return 0;
}
if(S_ISREG(buf.st_mode)){
printf("-");
}
if(S_ISDIR(buf.st_mode)){
printf("d");
}
if(S_ISCHR(buf.st_mode)){
printf("c");
}
if(S_ISBLK(buf.st_mode)){
printf("b");
}
if(S_ISFIFO(buf.st_mode)){
printf("p");
}
if(S_ISSOCK(buf.st_mode)){
printf("s");
}
// printf(" ");
int i;
for(i=8;i>=0;i--){
if(buf.st_mode & (1<<i)){
switch(i%3){
case 2:
printf("r");
break;
case 1:
printf("w");
break;
case 0:
printf("x");
break;
}
}else{
printf("-");
}
}
printf(" %d",(int)buf.st_size);
struct tm *t;
t = localtime(&buf.st_ctime);
printf(" %d-%d-%d %d:%d",t->tm_year+1900,t->tm_mon+1,t->tm_mday,t->tm_hour,t->tm_min);
printf(" chmod_t.c\n");
}
三、作业
遍历一个文件夹下所有文件,并打印文件大小和日期
#include <dirent.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
int main(int argc, char* argv[]) {
DIR * dp;
struct stat buf;
int ret;
struct dirent* dt;
dp = opendir("/home/linux/Desktop/work");//打开文件夹
if (dp == NULL) {
perror("opendir");
return 0;
}
while ((dt = readdir(dp)) != NULL) {
ret = stat(dt->d_name, &buf);
if (ret < 0) {
perror("stat");
return 0;
}
struct tm* t;
t = localtime(&buf.st_ctime);
printf(" %d-%d-%d %d:%d ", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min);
printf("name:%-16s size:%d\n", dt->d_name, ((int)buf.st_size));
}
closedir(dp);
return 0;
}