C & LINUX

C / LINUX getcwd(2) get_current_dir_name(2)

Ocean_ 2022. 5. 2. 19:21

함수 기능

현재 작업 디렉토리에 대한 전체 경로 이름을 얻을 수 있는 시스템 호출

get_current_dir_name = getcwd(NULL,0)

함수 원형

#include <unistd.h>
char *getcwd(char *buf, size_t size);
char *get_current_dir_name();

리턴 값 : 성공 시 현재 작업 디렉토리의 pathname, 에러시 null 리턴

함수 파라메터

BUF

현재작업디렉토리 경로저장할 버퍼

 

SIZE

버퍼 사이즈

함수 예제

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

#define PATH_MAX 1024

int main(void){
    char *pathname;

    if(chdir("/home/oslab")<0){
        fprintf(stderr, "chdir error\n");
        exit(1);
    }

    pathname = malloc(PATH_MAX);
    if(getcwd(pathname,PATH_MAX)==NULL){
        fprintf(stderr,"getcwd error\n");
        exit(1);
    }
    printf("current directory = %s\n",pathname);
    exit(0);
}

함수 결과

 

리눅스시스템 프로그래밍 - 홍지만 저

교재 내에 있는 예제를 바탕으로 작성한 글 입니다.