프로그래밍 언어/C, C++

[C언어] chdir 사용법

sujo 2022. 2. 9. 00:49

chdir 사용법

 

개요

현재 경로를 이동해주는 함수

man 2 chdir

 

 

사용법

1
2
3
#include <unistd.h>
 
int chdir(const char *path);
cs

 

  • 성공 시 0 리턴
  • 실패 시 -1 리턴

 

 

예제 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
 
void create_file()
{
    int fd;
 
    if ((fd = open("newfile",O_CREAT, 0644)) == -1)    
    {
        perror("open failed");
        exit(1);
    }
    close(fd);
}
 
int main(int argc, char *argv[])
{
    if (argc != 1)
    {
        int result = chdir(argv[1]);
        if (result == 0)
        {
            printf("success\n");
            create_file();
        }
        else
            printf("fail\n");
    }
    else
        printf("Error : Please enter the path\n");
    return (0);
}
cs

 

만약 해당하는 경로가 없으면 fail

해당하는 경로가 있다면 해당 디렉터리에서 파일을 하나 생성함.