The chdir function in C under Linux

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

int main(int argc, const char* argv[])
{
    
    
    if(argc < 2)
    {
    
    
        fprintf(stderr, "usage %s <dir>\n", argv[0]);
        return -1;
    }

    int ret = chdir(argv[1]);
    if(ret == -1)
    {
    
    
        perror("chdir");
        exit(1);
    }

    /* to verfy */
    int fd = open("chdir.txt", O_CREAT | O_RDWR, 0777);
    if(fd == -1)
    {
    
    
        perror("open");
        exit(1);
    }
    close(fd);

    char buf[128];
    getcwd(buf, sizeof(buf));
    
    printf("current dir: %s\n", buf);

    return 0;
}

Test Results

Insert picture description here

Guess you like

Origin blog.csdn.net/zxy131072/article/details/108533049