Hi there!

I am a student studying computer science.

시스템 프로그래밍

시스템 프로그래밍 2장 - Library call : File I/O function

만능성구 2020. 5. 5. 10:30
728x90

File Open

#include<stdio.h>

FILE *fopen(const char *filename, cosnt char *type);
file를 open하는 함수

filename : file이름 string 형태로

type : - r : read only

        - w : write (파일 사이즈를 zero), 새거 생성 가능

        - a : 쓰기가능인데 append if 기존 파일이 있으면 열어서 이어서 쓰고 없으면 생성

        - r+ : r/w

        - w+ : r/w 기존 파일이 있으면 file size를 0으로 or 새로 만들어서

        - a+ : r/append 기존파일이 있으면 이어서 없으면 생성

return 열린 file에 대한 file stream pointer / NULL

File Reopen

#include<stdio.h>

FILE *freopen(const char *filename, const char *type, FILE *stream);

현재 stream object arg로 넘겨 file을 close하고 filename으로 다시 opne해서 return해라

the original file descriptor is also reused!

 filename : file이름 string 형태로

type : - r : read only

        - w : write (파일 사이즈를 zero), 새거 생성 가능

        - a : 쓰기가능인데 append if 기존 파일이 있으면 열어서 이어서 쓰고 없으면 생성

        - r+ : r/w

        - w+ : r/w 기존 파일이 있으면 file size를 0으로 or 새로 만들어서

        - a+ : r/append 기존파일이 있으면 이어서 없으면 생성

stream : file pointer

return 열린 file에 대한 file stream pointer / NULL

z.B) freopen(“myfile.txt”,”w”,stdout);

      printf(“This…”);

      fclose(stdout);

File Close

#include<stdio.h>

int fclose(FILE *stream);

When a process exits normally, all files are automatically closed. 

If a process is terminated without closing a file,

• cannot check some errors that are reported by the fclose().

• file data in the library buffer might be lost.

만약에 open후 close하지 않으면 해당 file에 이상한 것이 써질 수 있다.

return 0 /  EOF 

File I/O functions

size_t fread(void *ptr, size_t size, size_tnitems, FILE *stream);

ptr : buffer의 주소

size : object의 unit byte size

size_tnitems : unit  object 수

stream : 어디서 읽을거야

 

return 읽은 byte 개수 (nitems) / 0

size_t fwrite(void *ptr, size_t size, size_tnitems, FILE *stream);

Character Input

int getc(FILE *stream);

int fgetc(FILE *strea);

file에서 character 씩 으로 읽는다.

return char를 integer type으로 / EOF

int getchar(void);

stdin에서 character 씩 으로 읽는다.

return char를 integer type으로 / EOF

char *fgets(char *s, int size, FILE *stream);

file에서 string으로 character를 size만큼 읽는다

return char stirng address / NULL

char *gets(char *s);

stdin에서 string을 읽어서 반환

return char stirng address / NULL

int ungetc(int c, FILE *stream);

character를 file에 다시 넣어준다.

return c / EOF

Character Output

int putc(int c, FILE *stream);

int fputc(int c, FILE *stream);

하나의 character를 file에 출력

return char를 integer type으로 / EOF
int putchar(int c);

하나의 character를 stdout에 출력

return char를 integer type으로 / EOF
int *fputs(const char *S, FILE *stream);

stirng으로 file에 출력

return char의 수 / EOF

char *puts(const char *s);

string을 stdout에 출력

return char의 수 / EOF

file i/o // 그냥 한글자씩 읽어서 사용

line i/o // buffering 사용, 한문장식 읽는다.

array i/o // 좋은 성능을 위해서 fread와 fwrite를 쓰는게 좀 더 효율적 대량의 데이터를 읽고 쓰기위해서는 구조화된 데이터를 쓸 필요가 있다.

struct i/o // 구조화된 객체를 쓰는 방법

filecopy // full buffer를 사용하는 것


offset란?

file이 열렸을 때 다음으로 접근할 위치!

- r/w는 file의 시작점

- a는 file의 끝점

- 이후 자동적으로 증가한다.

File Access Methods

  • Sequential access 순차적 증가
  • Random access 랜덤하게 증가
    • Library call의 경우 fseek(..), System call의 경우 lseek(..)를 이용하여 offset을 변경
      여까지는 연속적인 자료인 file에 대한 것
  • Keyed access
    • DB같은 경우는 key에 대하여 접근
int fseek(FILE *stream, long offset, int sopt);

offset 위치 변경

fseek로 rewind랑 ftell 커버 가능

stream : 파일 포인터

offset : 상대적거리

sopt : seek 옵션

           - SEEK_SET : offset

           - SEEK_CUR : current_offset + offset

            - SEEK_END : EOF+offset

return 0 / -1

void rewind(FILE *stream);

offset을 시작점으로 변경

return None / None

long ftell(FILE *stream);

현재 위치를 알려준다.

return 현재 위치 / -1

frandom

8L : 8 long..


I/O Types

  • Unformatted i/o
    • binary
    • 적혀있는 그대로 // 컴퓨터에게 편한
      • int 4byte
      • float 4byte
      • double 8byte
      • long 8byte
      • char 1byte
      • short 2byte
  • Formatting
    • text, 사람에게 편하게 변형한 형식, 대체적으로 ascii 코드
    • 보기쉽게 %f %5d "cat file"
int printf(const char *format,/* args */…);

consol, stdout에 출력

변경될 값을 argument로

retrun output length / negative integer
int fprintf(FILE *stream, const char *format, /* args */…);

파일에 출력

변경될 값을 argument로

retrun output length / negative integer

int sprintf(char *s, const *format, /* args */ …);

문자열 변수에 출력

file I/O는 아니다 

retrun output length / negative integer

int scanf(const cahr *format, …);

consol, stdin에서 읽기

retrun input length / EOF

int fscanf(File *stream, const char *format, …);

file에서 읽기

retrun input length / EOF

int sscanf(char *s, const char *format, ..);

string에서 읽기

retrun input length / EOF

stdio

file error check

에러를 다루는 함수 3가지

에러가 발생할때마다 종류별로 확인


int ferror(FILE *stream);

return nonzero value(종류 알려줄거임) / 0

int feof(FILE *stream);

파일의 끝인지 확인

return nonzero value(종류 알려줄거임) / 0

void clearerr(FILE *stream);

발생한  error를 지워라 지정된 error number 삭제

return None/ None

ferrror 파일읽어서 에러를 읽는다.

feof


Errror handling

특정 파일에 여러가지 error가 발생할 수 있다.

숫자에 따라서 다르게 정의되어있다.

#inclue <errno.h>

char *strerror(int errnum)
	//해당되는 error메시지를 string형태로 반환

#include<stdio..h>

void perror(const cahr *msg)
	//가장 최근에 error를 msg로 넘겨준다.
728x90