Linux应用开发-第三章Linux的目录IO

 一、目录IO和文件IO的对比

目录IO文件IO
opendir 打开目录open 打开文件
mkdir 创建目录
readdir 读目录read 读文件
closedir 关闭目录close 关闭文件

区别:文件IO和提到过的标准IO都是对文件操作,目录IO都是对目录的操作

二、目录IO具体函数

2.1 mkdir函数

函数介绍

/*
    #include <sys/stat.h>
    #include <sys/types.h>
    int mkdir(const char *pathname, mode_t mode);
        作用:创建一个目录
        参数:
            pathname: 创建的目录的路径
            mode: 权限,八进制的数
        返回值:
            成功返回0, 失败返回-1
*/

 实验:实验mkdir去创建一个aaa目录,权限是0777(因为是8进制,前面需要加0)

 实验代码

#include <sys/stat.h>
#include <sys/types.h>
#include<stdio.h>
int main(){

    int ret=mkdir("aaa", 0777);//这里虽然是0777(8进制),但是最终的权限是mode & ~umask & 0777
//做一个权限的消除,保证安全
    if (ret<0)
    {
        perror("mkdir");
        return -1;
    }
    return 0;
}

 实验现象

 2.2 rename函数

实验目的:我们把上一节创建的aaa目录改成bbb目录

 代码

#include <stdio.h>
/*实验目的:我们把上一节创建的aaa目录改成bbb目录*/
 
int main(){

    int ret=rename("aaa", "bbb");
    
    if (ret<0)
    {
        perror("rename");
        return -1;
    }
    return 0;
}

 实验现象

 2.3 chdir函数和getcwd函数

/*

    #include <unistd.h>
    int chdir(const char *path);
        作用:修改进程的工作目录
            比如在/home/nowcoder 启动了一个可执行程序a.out, 进程的工作目录 /home/nowcoder
        参数:
            path : 需要修改的工作目录

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

*/

 实验目的:获取当前的工作目录后再修改当前的工作目录

 代码

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

/*实验目的:获取当前的工作目录后再修改当前的工作目录*/
int main(){
    //获取当前的工作目录
    char buf[128];
    getcwd(buf,sizeof(buf));
    printf("当前的工作目录是:%s\n",buf);

    //修改工作目录
    int ret=chdir("/home/book/Linux/lesson13");
    //修改当前目录到指定目录,我们当前的目录是lesson14
    if(ret == -1) {
        perror("chdir");
        return -1;
    } 

    /*我们怎么样去判断我们切换路径有没有成功,就在lesson13目录下创建一个文件
    此时lesson13目录下为空
    */
    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));
    printf("修改后的工作目录是:%s\n",buf1);
    return 0;
}

 实验结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程者也

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值