본문 바로가기
TIL (Today I Learned)/컴퓨터 시스템(CS)

[CS] 표준 입출력, Standard IO #2

by 둥굴프 2022. 12. 14.
이 포스팅은 한국기술교육대학교 김덕수 교수님의 시스템 프로그래밍 (CSE 232)를 참고하여 작성되었습니다.

 

Standard IO <stdio.h>

- 플랫폼에 독립적인 유저 버퍼링 솔루션(user-buffering solution)이다.

- File pointer

File operation을 관리하는 구조체(FILE)를 가리키는 포인터

내부적으로 file descriptor와 연동(mapping)됨

- Stream

프로그램과 file을 연결하는 통로

Stream of bytes

 

Workflow of file I/O

- File open

파일 스트림 생성 및 FILE 구조체에 저장

fopen()

 

- File access (Read / Write)

파일의 내용 읽기 또는 정보 기록

fprintf(), fscanf(), fgetc(), fputc(), ...

 

- File close

파일에 대한 스트림 해제

 

#1 Opening a file/stream, fopen(3)

#include <stdio.h>
FILE *fopen(const char *filename, const char *mode);

path (file path) : 열려는 파일의 경로

mode (file open mode) : 파일 열기 모드

Return : file pointer / NULL = fail to open

 

Ascii (text) file & Binary file

- Ascii (text) file (텍스트 파일)

문자들이 들어 있는 표시 > 사람이 읽을 수 있는 형태

연속 적인 줄(line)로 구성되어 있음

각 문자는 ascii code로 표현됨

 

- Binary file (이진 파일)

이진 데이터가 직접 저장됨 > 사람이 그대로 읽기 어려운 형태

줄(line)로 구분되지 않는, 이진 데이터의 연속

컴퓨터가 읽을 수 있는 형태 > 데이터를 효율적으로 다룰 수 있음

 

#2 Closing a files/streams

#include <stdio.h>
int fclose(FILE *stream);

stream : 닫으려는 stream

Return : 0 = success / -1(EOF) = error

 

 

File open & close by Standard IO

#include <stdio.h>
#include <stdlib.h>

int main (void) {
    FILE *fp;
    
    // file open
    if ((fp = fopen("hello.txt", "w")) == NULL) {
        perror("fopen: hello.txt");
        exit(1);
    }

    // file close
    fclose(fp);

    return 0;
}

 

 

 

긴 글 읽어주셔서 감사드립니다.

22.12.14

댓글