基于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;
}
相关推荐
项目申报小狂人10 分钟前
算法应用上新!自适应更新策略差分进化算法求解球形多飞行器路径规划问题,附完整MATLAB代码
开发语言·算法·matlab
你好,赵志伟1 小时前
Socket 编程 TCP
linux·服务器·tcp/ip
Liang_GaRy2 小时前
心路历程-三个了解敲开linux的大门
linux·运维·服务器
一只栖枝6 小时前
华为 HCIE 大数据认证中 Linux 命令行的运用及价值
大数据·linux·运维·华为·华为认证·hcie·it
PAK向日葵6 小时前
【算法导论】PDD 0817笔试题题解
算法·面试
wuicer8 小时前
ubuntu 20.04 安装anaconda以及安装spyder
linux·运维·ubuntu
地平线开发者9 小时前
ReID/OSNet 算法模型量化转换实践
算法·自动驾驶
地平线开发者9 小时前
开发者说|EmbodiedGen:为具身智能打造可交互3D世界生成引擎
算法·自动驾驶
玩转以太网9 小时前
基于W55MH32Q-EVB 实现 HTTP 服务器配置 OLED 滚动显示信息
服务器·网络协议·http