[Unix] 시간 & 파일 관련 기초 함수 정리

붉을 혁 ,참 진·2024년 3월 31일
0

운영체제

목록 보기
2/3

  1. int stat(const char pathname, struct stat statbuf);

    ⇒ 파일명으로 파일 정보를 검색하는 함수이다.

    • ‘pathname’: 정보를 추출할 파일 명
    • ‘statbuf’: 검색한 파일 정보를 저장할 구조체 주소

    → 파일에 대한 읽기 권한이 주어져야 함

    → 성공시 0 반환 & stat 구조체에 파일 정보 저장, 실패시 -1 리턴

    • stat 구조체
    struct stat {
    	dev_t         st_dev;               //파일이 위치한 장치의 ID를 나타낸다.
    	ino_t         st_ino;               //파일의 inode(파일 시스템의 고유한 식별자)이다.
    	mode_t        st_mode;              //파일의 모드와 권한을 나타낸다.
    	nlink_t       st_nlink;             //파일에 대한 하드 링크 수를 나타낸다.
    	uid_t         st_uid;               //파일 소유자의 사용자 ID이다.
    	gid_t         stgid;                //파일 소유그룹의 그룹 ID읻
    	dev_t         st_rdev;              //파일이 시스템 외부 장치로연결된 경우, 해당 장치의 ID를 나타낸다
    	off_t         st_size;              //파일의 크기(바이트)를 나타낸다.
    	blksize_t     st_blksize;           //파일 시스템에서 사용하는 블록의 크기를 나타낸다.
    	blkcnt_t      st_blocks;            //파일이 사용하는 파일 시스템의 블록 갯수를 나타낸다.
    	time_t        st_atime;             //파일에 마지막으로 엑세스한 시간을 나타낸다.
    	time_t        st_mtime;             //파일의 마지막 수정 시간을 나타낸다.
    	time_t        st_ctime;             //파일의 마지막 변경 시간 (메타데이터 포함)을 나타낸다.
    };
  • inode란? 파일 시스템에서 파일을 식별하는데 사용되는 고유한 식별자이다. 파일의 메타데이터 및 데이터 블록 위치를 가리키는 포인터 역할을 한다.

  • 예시

       #include <stdio.h>
       #include <sys/stat.h>
    
       int main() {
        const char *pathname = "example.txt";
        struct stat statbuf;
    
        if (stat(pathname, &statbuf) == 0) {
            printf("File size: %lld bytes\n", (long long)statbuf.st_size);
            printf("File mode: %o\n", statbuf.st_mode);
            // 여기에 다른 파일 속성에 대한 출력 추가 가능
        } else {
            perror("stat");
            return 1;
        }
    
        return 0;
    }    
  1. struct tm localtime(const time_t timer);

    ⇒ 컴퓨터의 시간 (1970년 1월 1일 00시 00분 부터 지금까지의 초단위 시간 정수값)을 인간의 시간으로 변환시켜주는 함수

    → 성공시 tm 구조체 포인터가 반환된다; 실패시 NULL이 반한된다.

    #include <stdio.h>
    #include <time.h>
    int main() {
      time_t t;              //time_t는 ISO C라이브러리에서 시스템 시간을 저장하도록 정의 된 자료형이다. ㅅ
    												 //표준함수인 time()의 리턴값
      t = time(NULL);
      printf("%lld", t);
      return 0;
    }
    
    결과 값: 1711870258
    • tm 구조체
    struct tm {
       int tm_sec;         /* seconds,  range 0 to 59          */
       int tm_min;         /* minutes, range 0 to 59           */
       int tm_hour;        /* hours, range 0 to 23             */
       int tm_mday;        /* day of the month, range 1 to 31  */
       int tm_mon;         /* month, range 0 to 11             */
       int tm_year;        /* The number of years since 1900   */
       int tm_wday;        /* day of the week, range 0 to 6    */
       int tm_yday;        /* day in the year, range 0 to 365  */
       int tm_isdst;       /* daylight saving time             */	
    };
    • 예시 1
    #include <stdio.h>
    #include <time.h>
    
    int main() {
    	time_t rawtime;
    	struct tm *info;
    	time (&rawtime);
    	info = localtime (&rawtime); 
    	printf("Current local time and date: %s", asctime(info)); 
    	//asctime은 struct tm 구조체를 인수로 받아 해당 시간을 문자열로 변환한 후 반환한다.
    	
    	return 0;
    }
    
    결과 값: Current local time and date: Sun Mar 31 16:38:18 2024
    • 예시 2
    #include <stdio.h>
    #include <time.h>
    #include <sys/stat.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <fcntl.h>
    
    int main (int argc, char *argv[]) {
    struct stat statbuf;
    
    if(argc != 3) {
      printf("Error with arguments\n");
      exit(EXIT_FAILURE);
    }
    
    if (stat(argv[1], &statbuf) == -1){
      perror("Error: stat");
      exit(EXIT_FAILURE);
    } else {
      printf("st_dev = %ld\n", (long)statbuf.st_dev);
      printf("st_mode = %o\n", statbuf.st_mode);
      printf("st_uid = %d\n", statbuf.st_uid);
      printf("st_gid = %d\n", statbuf.st_gid);
      printf("st_size = %lld\n", (long long)statbuf.st_size);
      printf("st_mtime = %ld\n", (long)statbuf.st_mtime);
      //modified time
      struct tm *tm = localtime(&statbuf.st_mtime);
      printf("modified time = %d/%d/%d %02d:%02d:%02d\n", tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);
    }
    
    return 0;
    }
  2. int utime(const char filename, const struct utimbuf times);

    ⇒ Unix및 Unix 계열 시스템에서 파일의 마지막 접근 및 수정 시간을 변경하는데 사용된다.

    • ‘const char *filename’: 변경할 파일의 경로를 나타내는 문자열 포인터
    • ‘const struct utimbuf *times’: 파일의 새로운 접근 및 수정 시간을 지정하는 구조체 포인터

    → 성공시 0, 실패시 -1 반환

    • utimbuf 구조체
    struct utimbuf {
        time_t actime;  // 파일의 마지막 접근 시간을 나타내는 Unix 시간(epoch time)
        time_t modtime; // 파일의 마지막 수정 시간을 나타내는 Unix 시간(epoch time)
    };
  • 예시

     #include <stdio.h>
     #include <utime.h>
     #include <sys/stat.h>
     
     int main() {
     const char *filename = "example.txt";
     struct utimbuf times;
    
     // 새로운 액세스 및 수정 시간 설정 (예: 2024년 3월 31일 12시 30분 45초)
     times.actime = 1748793045; // 액세스 시간
     times.modtime = 1748793045; // 수정 시간
    
     // utime 함수 호출하여 파일의 액세스 및 수정 시간 설정
     if (utime(filename, &times) == 0) {
         printf("Access and modification times for file %s changed successfully.\n", filename);
     } else {
         perror("utime");
         return 1;
     }
    
     return 0;
    }
     
  1. int chmod (const char *pathname, mode_t mode);

    ⇒ 파일의 모드를 변경하는 데 사용된다.

    • ‘const char *pathname’: 모드를 변경할 파일의 경로를 나타내는 문자열 포인터
    • ‘mode_t mode’: 파일에 적용할 새로운 모드를 나타내는 값을 가진 변수입니다.
    • 파일 모드 표현 (읽기, 쓰기, 실행 순)
      • Onwer 권한: S_IRUSR, S_IWUSR, S_IXUSR
      • Group 권한: S_IRGPR, S_IWGRP, S_IXGRP
      • Other 권한: S_IROTH, S_IWOTH, S_IXOTH

    → 성공 0, 실패 -1 반환

    #include <stdio.h>
    #include <sys/stat.h>
    
    int main(){
    	const char *pathname = "example.txt";
    	mode_t new_mode = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IROTH; //744
    	
    	if (chmod(pathname, new_mode) == 0) {
    		printf("File mode changed successfully.\n");
    	} else {
    			perror("Error w/ chmod");
    			return 1;
    	}
    	
    	return 0;
    }
    
  1. int chown (const char* pathname, uid_t owner, gid_t group);

    ⇒ 파일의 소유자와 그룹을 변경하는데 사용된다.
    
    - ‘const char *pathname’: 모드를 변경할 파일의 경로를 나타내는 문자열 포인터
    - ‘uid_t owner’: 파일의 새로운 Owner의 ID를 나타내는 값
    - ‘gid_t group’: 파일의 새로운 Group의 ID를 나타내는 값
    
    → 성공 0, 실패 -1 반환
     #include <stdio.h>
     #include <unistd.h>
     int main(){
    	const char *pathname = "example.txt"
    	uid_t new_owner = 1000; // 예를 들어, 새로운 소유자의 사용자 ID가 1000이라 가정하면
    	gid_t new_group = 100; // 예를 들어, 새로운 그룹의 그룹 ID가 100이라 가정하면
    
    	if (chown(pathname, new_owner, new_group) == 0) {
    	  printf("File owner and groupd changed successfully.\n");
    	} else {
    			perror("chown");
    			return 1;
    	}
    	
    	return 0;
    }
profile
컴퓨터공학/경영 전공생 :)

0개의 댓글

관련 채용 정보