Linux-文件操作
文件操作
Linux文件结构
系统调用
库函数
底层文件访问
库函数
底层文件访问
标准I/O库
格式化输入和输出
文件和目录的维护
扫描目录
opendir函数
打开一个目录并建立一个目录流。如果成功,它返回一个指向DIR结构的指针,该指针用于读取目录数据项。
opendir在失败时返回一个空指针。
注意,目录流使用一个底层文件描述符来访问目录本身,所以打开的文件过多,opendir可能会失败。
#include <dirent.h>
#include <sys/types.h>
DIR *opendir(consrt char *name)
readdir()
telldir()
seekdir()
closedir()
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
void printdir(char *dir, int depth){
//int depth;
DIR *dp;
struct dirent *entry;
struct stat statbuf;
if((dp = opendir(dir)) == NULL ){
fprintf(stderr,"cannot open directory : %s\n" , dir);
return ;
}
chdir(dir);
while((entry = readdir(dp)) != NULL){
/*lstat(const char *path , struct stat *buf)获得一个与此命名文件有关的信息(到一个struct stat 类型的buf中)*/
lstat(entry -> d_name ,&statbuf);
if(S_ISDIR(statbuf.st_mode)){
//Found a directory ,but ignore . and ..
if( (strcmp ("." , entry -> d_name)) == 0 |
(strcmp("..",entry -> d_name) == 0))
continue;
printf("%*s%s\n",depth,"",entry->d_name);
//Recurse at a new indent level
printdir(entry -> d_name ,depth +4);
}
else printf("%*s%s\n",depth,"",entry->d_name);
}
chdir(".."); //chdir()用户当前的工作目录改变成以参数路径所指的目录
closedir(dp);
}
void chmdtxt(char *path ){
int cd;
cd = chmod(path, S_IRUSR | S_IWUSR | S_IRGRP);
printf("done!\n");
}
int main(){
char add[100];
gantt
printf("Directory scan of: \n");
scanf("%s", add);
printdir(add,0);
printf("\ndone!\n");
chmdtxt("/home/crowds/1.txt");
exit(0);
}