sliver__

[UNIX Input and Output] - Sparse Files 본문

CS/UNIX

[UNIX Input and Output] - Sparse Files

sliver__ 2022. 10. 11. 22:41
728x90

[Sparse Files]

  • sparse file은 sparse matrix 형식과 같다.
0 0 0 0 9
0 0 0 7 0
0 0 8 0 0
0 1 0 0 0
3 0 0 0 0
  • 위 행렬은 대부분 0이고 대각선 원소만 0이 아니다.
  • 25 cell을 모두 저장하는 것은 낭비이므로 non-diagonal 하게 저장한다.
  • sparse file도 마찬가지이다.
  • 아래는 sparse file을 만드는 예시이다.
1:   /* sparse.c */
2:
3:   #include <stdio.h>
4:   #include <fcntl.h>
5:   #include <unistd.h>
6:   #include <errno.h>
7:   #include <string.h>
8:   #include <sys/types.h>
9:   #include <sys/uio.h>
10:
11:  int
12:  main(int argc,char **argv) {
13:      int z;                              /* Return status code */
14:      off_t o;                            /* Offset */
15:      int fd;                             /* Read file descriptor */
16:
17:      /*
18:       * Create/truncate sparse.dat
19:       */
20:      fd = open("sparse.dat",O_CREAT|O_WRONLY|O_TRUNC,0640);
21:      if ( fd == -1 ) {
22:          fprintf(stderr,"%s: opening sparse.dat for write\n",
23:              strerror(errno));
24:          return 1;                       /* Failed */
25:      }
26:
27:      /*
28:       * Seek to almost the 1GB mark :
29:       */
30:      o = lseek(fd,1023*1024*1024,SEEK_SET); /* Seek to ~1GB */
31:      if ( o == (off_t)(-1) ) {
32:          fprintf(stderr,"%s: lseek(2)\n",strerror(errno));
33:          return 2;
34:      }
35:
36:      /*
37:       * Write a little message :
38:       */
39:      z = write(fd,"END-OF-SPARSE-FILE",18);
40:      if ( z == -1 ) {
41:          fprintf(stderr,"%s: write(2)\n",strerror(errno));
42:          return 2;
43:      }
44:
45:      close(fd);                          /* Close the file */
46:
47:      return 0;
48:  }
$ make sparse
cc -c -D_POSIX_C_SOURCE=199309L -Wall sparse.c
cc sparse.o -o sparse
$ ./sparse
$ ls -l sparse.dat
-rw-r-----  1 me   mygrp 1072693266 Apr 17 02:36 sparse.dat
$ od -cx sparse.dat
0000000   \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0
            0000    0000    0000    0000    0000    0000    0000    0000
*
7774000000    E   N   D   -   O   F   -   S   P   A   R   S   E   -   F   I
            4e45    2d44    464f    532d    4150    5352    2d45    4946
7774000020    L   E                                                       
            454c                                                       
7774000022
$
  • ls로 sparse.dat size를 확인한 결과 약 1GB이다.
  • od 명령어는 파일을 dump 뜨는 명령어이다. -cx 옵션을 주어 16진수로 표현하였다.
  • 왼쪽의 숫자는 offset을 의미한다.
728x90
Comments