본문 바로가기
호기심_메모

UNIX 메뉴얼에 나와있는 명세(specification)를 참조하여, chmod 작성

by 겸손, 빚진자, 늘 배우는 사람, 배운것을 실습해보는 사람 2021. 8. 13.
반응형

#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <fcntl.h>

#include <sys/stat.h>

 

int lsoct(char* perm)

{

int i, j, k,oct=0;

 

if(perm[0] == 'r') oct += 400;

if(perm[1] == 'w') oct += 200;

if(perm[2] == 'x') oct += 100;

if(perm[3] == 'r') oct += 40;

if(perm[4] == 'w') oct += 20;

if(perm[5] == 'x') oct += 10;

if(perm[6] == 'r') oct += 4;

if(perm[7] == 'w') oct += 2;

if(perm[8] == 'x') oct += 1;

 

i = oct % 10;

oct /= 10;

j = oct % 10;

oct /= 10;

k = oct % 10;

 

return(k*8*8+j*8+i);

}

 

main(int argc, char* argv[])

{

mode_t i, j, k, temp, perm;

struct stat statbuf;

int p;

 

static short octarray[9] = { 0400, 0200, 0100, 0040, 0020, 0010,

0004, 0002, 0001 };

 

if(argc != 3)

{

perror("wrong arguments");

exit(1);

}

if( open(argv[2], O_RDONLY) == -1)

{

perror("file don't exist");

exit(1);

}

 

if( argv[1][0] >= '0' && argv[1][0] <'9' )

{

temp = atoi(argv[1]);

i = temp % 10;

temp /= 10;

j = temp % 10;

temp /= 10;

k = temp % 10;

 

perm = k*8*8 + j*8 + i;

}

else if( argv[1][1] == '+' || argv[1][1] == '-' )

{

if( stat (argv[2], &statbuf ) == -1)

{

fprintf(stderr, "couldn't stat %s\n", argv[2]);

exit(1);

}

 

switch( argv[1][0] ){

case 'u': p = 0; break;

case 'g': p = 3; break;

case 'o': p = 6; break;

default : fprintf(stderr, "wrong argument\n"); exit(1);

}

 

switch( argv[1][2] ) {

case 'r': p += 0; break;

case 'w': p += 1; break;

case 'x': p += 2; break;

default : fprintf(stderr, "wrong argument\n"); exit(1);

}

 

if( argv[1][1] == '+' )

statbuf.st_mode |= octarray[p];

else if( argv[1][1] == '-' )

statbuf.st_mode ^= octarray[p];

else

{

fprintf(stderr, "wrong argument\n"); exit(1);

}

 

if (chmod (argv[2], statbuf.st_mode ) == -1 )

fprintf(stderr, "couldn't change mode for %s\n", argv[2]);

exit(1);

}

else

perm = lsoct(argv[1]);

 

if( chmod(argv[2], perm ) == -1)

{

perror("call to chmod failed");

exit(1);

}

 

printf("om101's chmod ver 1.0\n");

}

728x90