pwd

윤강훈·2024년 10월 17일

System Programming

목록 보기
5/12

pwd

  • 현재 작업 디렉토리의 경로를 출력

  • 현재 자신의 디렉토리는 "."로 표현하며 inode 번호를 가지고 있음

  • 디렉토리는 연결된 노드(디렉토리)들의 집합

how works

  • 아래 3개의 과정을 최상위 디렉토리에 도달할 때까지 반복

    1. 현재 디렉토리(".")에 대한 inode 번호 n을 확인(stat 호출)

    2. chdir .. (chdir 호출)

    3. inode 번호 n과 연결된 이름을 찾음 (opendir, readdir, closedir)

code

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

ino_t get_inode(char *);
void print_path_to(ino_t);
void inode_to_name(ino_t, char *, int);

int main(){
    print_path_to(get_inode("."));
    putchar('\n');
    return 0;
}

ino_t get_inode(char *filename){
    struct stat info;
    if (stat(filename, &info) == -1){
        fprintf(stderr, "cannot stat ");
        perror(NULL);
        exit(-1);
    }
    return info.st_ino;
}

void print_path_to(ino_t inode){
    ino_t my_inode = 0;
    char its_name[256];

    if (get_inode("..") != inode){
        chdir("..");
        inode_to_name(inode, its_name, 256);
        my_inode = get_inode(".");
        print_path_to(my_inode);
        printf("/%s", its_name);
    }
}

void inode_to_name(ino_t inode_to_find, char *namebuf, int buflen){
    DIR *dir_ptr = NULL;
    struct dirent *dirent_ptr = NULL;

    if ((dir_ptr = opendir(".")) == NULL){
        perror(NULL);
        exit(-1);
    }

    while((dirent_ptr = readdir(dir_ptr)) != NULL){
        if (dirent_ptr->d_ino == inode_to_find){
            strncpy(namebuf, dirent_ptr->d_name, buflen);
            closedir(dir_ptr);
            namebuf[buflen-1] = '\0';
            return;
        }
    }
    fprintf(stderr, "error looking for inode: %ld\n", inode_to_find);
    exit(1);
}

함수 설명

  1. get_inode: 해당하는 디렉토리의 inode 번호를 가져옴

  2. print_path_to: 상위 디렉토리로 재귀적으로 올라가며 최상위 디렉토리에 도달했을 경우 돌아오며 출력

  3. inode_to_name: inode번호를 통해 현재 디렉토리의 이름을 버퍼에 저장

profile
Just do it.

0개의 댓글