基于linux下的高并发服务器开发(第一章)- 目录操作函数

09 / 目录操作函数

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

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

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

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

int main() {

    int ret = mkdir("aaa", 0777);

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

    return 0;
}

(1)gcc mkdir.c -o mkdir

(2)./mkdir

(2)int rename(const char *oldpath, const char *newpath);

cpp 复制代码
/*
    #include <stdio.h>
    int rename(const char *oldpath, const char *newpath);

*/
#include <stdio.h>

int main() {

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

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

    return 0;
}

(3)int chdir(const char *path);

char *getcwd(char *buf, size_t size);

#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: 数组的大小
    返回值:
    返回的指向的一块内存,这个数据就是第一个参数**
cpp 复制代码
/*

    #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/stat.h>
#include <sys/types.h>
#include <fcntl.h>

int main() {

    // 获取当前的工作目录
    char buf[128];
    getcwd(buf, sizeof(buf));
    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));
    printf("当前的工作目录是:%s\n", buf1);
    
    return 0;
}
相关推荐
Stringzhua10 分钟前
Linux Docker下安装tomcat
linux·docker·tomcat
asom2211 分钟前
LeetCode Hot100(字串)
算法·leetcode
wanhengidc42 分钟前
怎样判断服务器网络质量的状态?
运维·服务器
luckyext1 小时前
SQL的RAND用法和指定生成随机数的范围
运维·服务器·数据库·sql·sqlserver·运维开发·mssql
学习使我变快乐2 小时前
C++:无序容器
数据结构·c++·算法
朱剑君2 小时前
贪心算法——分数背包问题
算法·贪心算法
小O的算法实验室2 小时前
2008年EJOR SCI2区,连续蚁群优化算法ACOR,深度解析+性能实测
算法·智能算法
2301_794461572 小时前
力扣-将x减到0的最小操作数
数据结构·算法·leetcode
bing_feilong2 小时前
树莓派4B搭建Hector SLAM算法, ROS1 & ROS2?
算法·机器人
炫酷的伊莉娜2 小时前
【Linux cmd】查看 CPU 使用率的几个命令
linux