공부/리눅스

리눅스 하드 링크, 심볼릭 링크, 디렉터리 만들기

choryDev 2019. 10. 2. 17:04

하드 링크

원본 파일과 새로 만든 링크와 같은 inode를 참조한다.

 

하드링크 생성 및 조회하는 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
 
int main(void){
    struct stat buf;
 
    stat("unix.txt",&buf);
    printf("Before Link Count = %d\n", (int)buf.st_nlink);
 
    link("unix.txt","unix.ln");
 
    stat("unix.txt",&buf);
    printf("After Lunk Count = %d\n", (int)buf.st_nlink);
 
    return 0;
}
cs

 

심볼릭 링크

기준 파일에 접근하는 다른 파일 생성, 기존파일의 데이터 영역 주소 값만 포함
(다른 inode 사용)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
 
int main(void){
    struct stat buf;
 
    stat("unix.txt",&buf);
    printf("Before Link Count = %d\n", (int)buf.st_nlink);
 
    symlink("unix.txt","unix.sln");
 
    stat("unix.txt",&buf);
    printf("After Lunk Count = %d\n", (int)buf.st_nlink);
 
    return 0;
}
cs

 

디렉터리

디렉터리 생성 및 이름변경, 삭제 코드

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
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
 
int main(void){
    if(mkdir("ch05_test"0755== -1) {
    //야무지게 디렉터리 만들기 
        perror("first make dir");
        exit(1);
    }
    if(mkdir("ch05_new"0755== -1) {
    //야무지게 디렉터리 만들기 
        perror("second make dir");
        exit(1);
    }
    if(rename("ch05_new""ch05_old"== -1) {
    //야무지게 디렉터리 이름 바꾸기  
        perror("third make dir");
        exit(1);
    }
    if(rmdir("ch05_test"== -1) {
    //야무지게 디렉터리 지우기 
        perror("remove dir");
        exit(1);
    }
    return 0;
}
 
cs