您的位置:首页 > 运维架构 > Linux

linux文件与目录操作相关API及递归遍历目录

2013-02-25 12:02 651 查看
1.文件与目录操作主要API

@ int chmod(const char *path, mode_t mode) 改变目录或文件访问权限;

@ int chown(const char *path, uid_t owner, gid_t group)改变文件属主

@ int mkdir(const char *path, mode_t mode)创建目录

@ int rmdir(const char *path)删除目录

@ int chdir(const char *path)切换目录

@ char * getcwd(char *buf, size_t size)获取当前目录

@ DIR *opendir(const char *name)打开目录建立目录流,使用返回的目录流完成目录操作,类似于文件指针

@ struct dirent *readdir(DIR *dirp)返回一个指向目录项的资料结构

@ int closedir(DIR *dirp)关闭一个目录流并释放相关资源

2.类似深度遍历的目录扫描方法

void printdir(char *dir, int depth)

{

DIR *dp;

struct dirent *entry;

struct stat statbuf;

if((dp = opendir(dir)) == NULL)

{

fprintf(stderr,"invalid dir: %s\n",dir);

return;

}

chdir(dir);

while((entry = readdir(dp)) != NULL)

{

lstat(entry->d_name, &statbuf);

if(S_ISDIR(statbuf.st_mode))

{

if(strcmp(".",entry->d_name) == 0 ||

strcmp("..",entry->d_name) == 0)

continue;

printf("%*s%s/\n",depth,"",entry->d_name);

printdir(entry->d_name,depth+2); //递归调用遍历当前子目录

}

else

printf("%*s%s\n",depth,"",entry->d_name);

}

chdir("..");
//一个子目录遍历结束,返回上一级目录

closedir(dp);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: