파일 입출력

TAEWOO HA·2023년 5월 2일
0

File

목록 보기
1/3

File

보조 기억장치에 저장된 정보들의 집합

  • 보조 기억 장치 할당의 최소 단위

  • Sequence of bytes(물리적 정의)

  • OS는 file operation들에 대한 system call을 제공해야함

Low-level vs High level File IO

  1. Low level
  • 시스템 콜을 이용해서 파일 입출력
  • 파일 디스크립터 사용
  • 바이트 단위로 디스크에 입출력
  • 특수 파일에 대한 입출력 가능
  1. Hight level
  2. C를 사용하여 파일 입출력 수행
  3. 파일 포인터 사용
  4. 버퍼(블록) 단위로 디스크에 입출력

Opening Files

#include <sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>

int open (const char *pathname, int flags [,mode_t mode]);
  • pathname : 열려는 파일의 경로 (파일 이름 포함)
  • flags : 파일을 여는 방법
  • mode : 파일을 새로 생성할 때만 유효
  • Return : file descriptor

Consing Files

#include <unistd.h>

int close (int fd);
  • fd : 닫으려는 file descriptor

  • return 0 : success -1 : error

Open & Close a file

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

int main(){
	int fd; // 파일 디스크립터 저장
    mode_t mode; // 모드t 변수타입 사용
    
    mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH
    
    fd = open("hello.txt",O_CREAT, mode); //644
    if (fd == -1){
    	perror("Creat"); exit(1);
    } // 파일이름,access, 모드
    close(fd);
    
    return 0;
}

O_EXCL 사용해보기

int main(void){
	int fd;
    
    fd= open("hello.txt", O_CREAT|O_EXCL,0644);
    if(fd == -1){
    	perror("EXCL");
        exit(1);
    }
    close(fd);
    
    return 0;
}

0개의 댓글