Linux学习第六天(目录操作函数)

本文介绍了Linux系统中用于目录操作的几个关键函数:mkdir用于创建目录,rmdir删除空目录,rename修改目录名,而chdir则用于改变进程的工作目录。同时,文章通过示例代码展示了如何使用这些函数,并提到了open函数来创建文件。
摘要由CSDN通过智能技术生成
  1. mkdir函数

作用:创建一个空目录

#include<sys/stat.h>
#include<sys/types.h>
int mkdir(const char *pathname,mode_t mode)
    -mode:需要修改的权限值(8进制)
    -0成功,-1失败

补充:在linux中输入

rm dir 

只能够删除空目录,并不能删除有内容的目录

如果想要删除非空目录,需要使用

rm -r dir

示例代码

#include <sys/stat.h>
#include <sys/types.h>
#include <stdio.h>

int main() {
    //在当前工作目录下新建一个aaa文件夹
    int ret = mkdir("aaa", 0777);//与umask0002操作,抹除非本组的写权限
    //d rwxrwxr-x
    if(ret == -1) {
        perror("mkdir");
        return -1;
    }

    return 0;
}
  1. rename函数

作用:修改目录的名字

#include <stdio.h>
int rename(const char *oldpath, const char *newpath);
    成功返回0,失败返回-1并设置errno
//将当前目录下一个叫aaa的文件夹重命名为bbb
int main() {

    int ret = rename("aaa", "bbb");

    if(ret == -1) {
        perror("rename");
        return -1;
    }

    return 0;
}
  1. chdir函数

作用:修改进程的工作目录

比如在/home/nowcoder 启动了一个可执行程序a.out, 进程的工作目录 /home/nowcoder

我们需要使用getcwd函数获取当前的工作路径

 #include <unistd.h>
 int chdir(const char *path);
     参数:
         path : 需要修改的工作目录

 #include <unistd.h>
 char *getcwd(char *buf, size_t size);
     作用:获取当前工作目录
     参数:
         - buf : 存储的路径,指向的是一个数组(传出参数)
         - size: 数组的大小
     返回值:
         返回的指向的一块内存,这个数据就是第一个参数
#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>

int main() {

    // 获取当前的工作目录
    char buf[128];
    getcwd(buf, sizeof(buf));//当前的工作目录存储在buf中
    //  /home/nowcoder/Linux/lesson13
    printf("当前的工作目录是:%s\n", buf);

    // 修改工作目录
    int ret = chdir("/home/nowcoder/Linux/lesson13");
    if(ret == -1) {
        perror("chdir");
        return -1;
    } 

    // 在新进入的工作目录中,创建一个新的文件
    int fd = open("chdir.txt", O_CREAT | O_RDWR, 0664);
    if(fd == -1) {
        perror("open");
        return -1;
    }

    close(fd);

    // 获取当前的工作目录
    char buf1[128];
    getcwd(buf1, sizeof(buf1));
    // /home/nowcoder/Linux/lesson13
    printf("当前的工作目录是:%s\n", buf1);
    
    return 0;
}

在上面的示例代码中,我们运行的程序目录由lesson14切换到了lesson13并在其中创建了一个新的文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值