step4 . day3 目录访问函数
和標準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\n",dent->d_name);
}
closedir(dirp);
return 0;
}
轉載于:https://www.cnblogs.com/huiji12321/p/11305698.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的step4 . day3 目录访问函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 致27岁的老光棍天空
- 下一篇: step4 . day4 库函数和库函数