See struct stat and fstat;

pretty simple example, and getMode show a good example in terms of bit operation.



#include <stdio.h>              // 표준입출력헤더파일

   #include <stdlib.h>            

   #include <sys/stat.h>           // stat 구조체가선언되어있는헤더파일

   #include <sys/types.h>          // perror 함수호출을위한헤더파일

   #include <unistd.h>

   #include <fcntl.h>              // file control flag가저장되어있는헤더파일

 

   #define MAX_BUF 64              // BUF 크기를정의한다.

 

  char* getMode(mode_t mode,char* bit);   // getMode 함수는현재파일의속성을출력한다.

 

  int main(int argc, char *argv[])        // 메인함수시작

  {

      int fdForRead;                     // file descriptor for read

      int fdForWrite;                    // file descriptor for write

      char buf[MAX_BUF];                 // to define buffer

      int read_size;                     // readoff셋으로활용되는변수

      int write_size;                           // wrtieoff셋으로활용될변수

      struct stat info;                  // 파일의정보를받을구조체

      int fs;                                   // fstat의리턴값을저장할변수

      int modeInfo;                      // getModemode를받을정수

      char bit[10];                             // rwxrwxrwx로출력하기위한변수

      int i=0;                           // for문의counter 변수

 

      if(argc != 3)                      // 만약arument의사용법이잘못됐다면

      {

          printf("Usage : mycp.out source_file_name destination_file_name\n\n");

                                         // 사용법을알려준후

          exit(-1);                      // 프로그램을종료한다.

      }

 

      fdForRead = open(argv[1], O_RDWR);   // 2번째argument를이용해서파일을열며읽기쓰기가능>

      if(fdForRead <0){                                // 만약읽기가실패한다면

          perror("cannot open the file because : ");  // 메세지를출력후

          exit(-1);                                    // 프로그램을종료한다.

     }

 

     printf("\n\nThis program is coping a file with the mode of file \n");

                                                         // 프로그램실행전출력메세지

 

     fstat(fdForRead, &info);    //fstat      수는file descriptor를이용하여stat 구조체에

                                 // file에대한정보를저장하며여기서우리는mode를얻을수있다.

 

     getMode(info.st_mode,bit);          // getMode는가져온mode정보를rwxrwxrwx 형태로bit에대입한다.

     printf("The mode = %s \n\n",bit);     // 현재파일의모드를출력하고

 

 

/*************************************************************************************

//                         Redirection

 

     // close(STDOUT_FILENO);    // 만약redirection을쓰고싶으면이주석을해제하면된다.

 

 ************************************************************************************/

 

 

     fdForWrite = open(argv[2], O_RDWR | O_CREAT | O_EXCL, info.st_mode);

                                           // stat 구조체에저장된st_mode를이용하여파일을생성하며

                                           // 만약파일명이중복된다면O_EXCL flag로인하여파일이생성되지않>

     if(fdForWrite == -1){                 // 파일생성에실패하거나파일이존재한다면

         perror("cannot open the file because :  ");     // 메세지와errno의메세지를같이출력한후

         exit(-1);                           // 프로그램을종료한다.

     }

      while(1){                                     // while문은파일이다써질때까지반복되며

          read_size = read(fdForRead, buf, MAX_BUF);  // 64바이트씩파일을읽는다

          if(read_size == 0)                       // 만약파일의끝이라면

              break;                               // 반복문을빠져나간다.

          write_size = write(fdForWrite, buf, read_size);     // 64바이트씩새로운file에쓴다.

 

         /******************** Redirection ******************************

                    

          //write_size = write(STDOUT_FILENO, buf, read_size);    // redirection을이용한file 출력

 

         ***************************************************************/    

 }

      printf("Successful!\n");     // 파일복사가완료되면메세지를생성후

      close(fdForRead);             // file descriptor들을닫아준다.

      close(fdForWrite);

      return 0;

  }

 

   char* getMode(mode_t mode,char* bit)       // file mode를출력하는함수

  {

      int i=0;                            // 반복문의counter

      int index=0;                        // index는문자를저장할떄쓰인다

      int modeInfo = 00777 & (unsigned long)mode;     // 777modeAND 연산한후

      for(i=256;i>0;i=i/2){                     // 그내용들을출력하는반복문을실행한다.

          if((modeInfo & i) == i)        // 만약i2^8부터2^0까지바뀌게되며

          {                              // and 연산이i값과같다면그flagset이다.

              if(index%3 == 0)                  // rwx 위치에맞게문자열에저장된다.

                  bit[index] = 'r';

              else if(index%3 == 1)

                  bit[index] = 'w';

              else

                  bit[index] = 'x';

          }

          else

              bit[index] = '-';          // 만약flag0이라면'-'로문자열을채운다.

          index++;                       // index를증가시킨후

      }

      return bit;                     // 받았던문자열을반환한다.

}


'Programming > System programming' 카테고리의 다른 글

dup2() and pipe() system call for pipe fuction in shell  (1) 2011.11.03
sys/types.h  (2) 2011.10.10
Posted by 박세범