Linux:目录操作文件

Linux:目录操作文件

在这里插入图片描述

mkdir

/*
#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("./test1", 0777);

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

    return 0;
}

rename

/*
#include <stdio.h>
int rename(const char *oldpath, const char *newpath);
*/
#include <stdio.h>

int main(){
    
    


    int ret = rename("./test1", "./test2");

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



    return 0;
}

小综合

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


char *getcwd(char *buf, size_t size);
作用:
    获取当前工作目录
参数:
    buf: 保存目录的路径,char数组
    size: sizeof(buf)
返回值:
    指向的一块内存即buf

char *getwd(char *buf);
char *get_current_dir_name(void);

*/
#include <stdio.h>
#include <unistd.h>
#include <string.h>

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

int main(){
    
    

    char buf[1024];

    //获取当前工作目录
    getcwd(buf, sizeof(buf));
    printf("当前工作目录为: %s \n", buf);

    //修改目录
    int ret = chdir("/home/carey/Linux/chdir");

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

    //创建新文件
    int fd = open("chdir.txt", O_CREAT | O_RDWR, 0664);
    if(fd == -1){
    
    
        perror("open");
        return -2;
    }

    close(fd);

    //获取当前工作目录
    char buf1[1024];
    getcwd(buf1, sizeof(buf1));
    printf("当前工作目录为: %s \n", buf1);

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_44861043/article/details/121371468