linux 退出目录,linux 目录

创建和删除

int mkdir(const char *pathname, mode_t mode);

int rmdir(const char *pathname);

另外remove也可以删除文件夹

mode: S_IRUSR,S_IWUSR,S_IXUSR,S_IRGRP,S_IWGRP,S_IXGRP,S_IROTH,S_IWOTH,S_XOTH

S_IRWXU,S_IRWXG,S_IRWXO

char *pathname="./newfolder";

if(mkdir(pathname,S_IRWXU|S_IRGRP|S_IWGRP|S_IROTH)<0){

perror("mkdir failed");

exit(1);

}else

printf("mkdir success");

if(rmdir(pathname)<0){

perror("rmdir failed");

exit(1);

}else

printf("rmdir success");

打开,读取,关闭

目录以DIR来表示, 有点类似FILE, 读FILE返回char, 读目录返回dirent结构

dirent结构有两个重要属性:

ino_t d_ino; // i节点信息, 文件或文件属性

char d_name[]; //文件或文件夹名称

打开文件夹: DIR *opendir(pathname)

关闭文件夹: int closedir(pathname)

读取文件夹: struct dirent *readdir(DIR *dp)

// #include

DIR *curdir;

char *path=".";

if((curdir=opendir(path)) == NULL){

perror("opendir failed");

exit(1);

}else

printf("opendir success\n");

struct dirent *dirp;

while((dirp=readdir(curdir)) != NULL)

printf("%s\n",dirp->d_name);

if(closedir(curdir) <0){

perror("closedir failed");

exit(1);

}else

printf("closedir success\n");

切换目录

获取当前目录名称: char *getcwd(char *buf, size_t size);

切换目录: int char(const char *pathname);

char buf[256];

if(getcwd(buf,256) == NULL){

perror("getcwd failed");

exit(1);

}else

printf("current dir : %s\n", buf);

char *parent="..";

if(chdir(parent) <0){

perror("chdir failed");

exit(1);

}else

printf("current dir: %s\n",getcwd(buf,256));

遍历文件夹例子

注意点:

进入子目录时用到chdir(childpath)

子目录遍历后要返回父目录chdir("..")

printf("%*s",5,char* s)=prinf("%5s,char *s)

表示打印s时占据5个字母的宽度,超过设定的值时全部打印

#include

#include

#include

#include

#include

#include

#include

#include

void scan_dir(char *dir, int depth){ //depth用于缩进

DIR *dp;

struct dirent *entry;

struct stat statbuf;

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

perror("opendir failed");

exit(1);

}

if(chdir(dir) <0){ //切换目录, 切换到子目录

perror("chdir failed");

exit(1);

}

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); // 输出目录名称

scan_dir(entry->d_name, depth+4); // 递归调用自身,扫描下一级目录的内容

}else

printf("%*s%s\n", depth, "", entry->d_name); //如果不是目录就只打印文件名

}

if(chdir("..") <0){ // 回到上级目录

perror("chdir failed");

exit(1);

}

if(closedir(dp) <0){ //关闭目录 perror("closedir failed");

exit(1);

}

}

int main(){

puts("scan /home:");

scan_dir("/root", 0);

puts("scan over.");

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值