和标准IO访问文件类似,Linux本着万物皆文件的原则,对文件进行访问。
涉及相关函数:DIR * opendir closedir readdir chmod fchmod stat lstat fstat getpwuid getgrpid
练习demo:按照ls命令的输出,使用stat函数实现。
#include <stdio.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#include <pwd.h>
#include <grp.h>
int main(int argc, const char *argv[])
{
DIR *dirp;
struct dirent *dent;
struct stat buf;
struct tm *t;
char *month[] = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug",
"Sept","Oct","Nov","Dec"};
dirp = opendir("/home/linux/step4/day2");
if(dirp == NULL){
perror("opendir");
return -1;
}
while((dent = readdir(dirp)) != NULL){
lstat(dent->d_name,&buf);
if(S_ISREG(buf.st_mode)) printf("-");
else if(S_ISDIR(buf.st_mode)) printf("d");
else if(S_ISCHR(buf.st_mode)) printf("c");
else if(S_ISBLK(buf.st_mode)) printf("b");
else if(S_ISFIFO(buf.st_mode)) printf("p");
else if(S_ISLNK(buf.st_mode)) printf("l");
else printf("s");
if(S_IRUSR & buf.st_mode) printf("r");
else printf("-");
if(S_IWUSR & buf.st_mode) printf("w");
else printf("-");
if(S_IXUSR & buf.st_mode) printf("x");
else printf("-");
if(S_IRGRP & buf.st_mode) printf("r");
else printf("-");
if(S_IWGRP & buf.st_mode) printf("w");
else printf("-");
if(S_IXGRP & buf.st_mode) printf("x");
else printf("-");
if(S_IROTH & buf.st_mode) printf("r");
else printf("-");
if(S_IWOTH & buf.st_mode) printf("w");
else printf("-");
if(S_IXOTH & buf.st_mode) printf("x");
else printf("-");
printf("%2d",buf.st_nlink);
printf(" %s %s",getpwuid(buf.st_uid)->pw_name,getgrgid(buf.st_gid)->gr_name);
printf(" %6ld",buf.st_size);
t = localtime(&(buf.st_atime));
printf(" %s %2d %02d:%02d",month[t->tm_mon],t->tm_mday,t->tm_hour,t->tm_sec);
printf(" %s
",dent->d_name);
}
closedir(dirp);
return 0;
}