14. fiile io

36
File I/O

Upload: -

Post on 19-May-2015

75 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: 14. fiile io

File I/O

Page 2: 14. fiile io

2

File 입출력§ 지금까지의프로그램입출력

– 입력: Keyboard– 출력: Monitor

§ 필요한자료를파일에서읽어서출력을파일로할수없을까?

국 영 수1 80 90 702 80 60 403 60 50 70

C program

국 영 수 평균1 80 90 70 802 80 60 40 603 60 50 70 60

Page 3: 14. fiile io

3

File 입출력§ 파일을이용한입출력절차

해당 파일 열기

파일에서 읽기파일에 쓰기

파일 닫기

fopen

fscanf, fprintf, fgets, fputs, …

fclose

Page 4: 14. fiile io

4

File Operation Function fopen()

§ fopen()– 외부 file을 프로그램에서사용하기 위해 준비시키는 명령– 입력에 이용될 모든 파일은 fopen을통하여 준비되어야 함– Return값: FILE 구조체의 pointer

• 파일에 대한 읽기 혹은 쓰기는 fopen이 반환한 FILE pointer를통해서 이루어짐

§ fopen() SyntaxFILE *fopen( const char *filename, const char *mode );

file pointer로 return disk에 있는 filename file open시의 mode

Page 5: 14. fiile io

5

File Operation Function fopen()

§ fopen() 예제– 파일에서 자료를 읽기 위해서 파일을 준비 시킬 때

– my_file.txt을읽기모드로 준비 함

– 만약 파일이 없으면 NULL이 반환됨

FILE *fp ;fp = fopen(“my_file.txt”, “r”);

Page 6: 14. fiile io

6

File Operation Function fopen()

§ fopen() 예제– 파일에 자료를 쓰기 위해서 파일을 준비 시킬 때

– my_file.txt를쓰기모드로 준비시킴

– 만약 파일이 없으면 my_file.txt이생성됨– 만약 이미 my_file.txt가존재하면, 그 안에 있는 모든 내용이지워짐

FILE *fp ;fp = fopen(“my_file.txt”, “w”);

Page 7: 14. fiile io

7

File Operation Function fopen()

§ fopen() 예제– 파일에 자료를 추가로 쓰기 위해서 파일을 준비 시킬 때

– my_file.txt를 append모드로준비시킴

– 만약 파일이 없으면 my_file.txt이생성됨– 만약 이미 my_file.txt가존재하면, 기존의 내용은 그대로 유지되고 새로 쓰여지는 것은 파일 마지막에 추가됨

FILE *fp ;fp = fopen(“my_file.txt”, “a”);

Page 8: 14. fiile io

8

File Operation Function fopen()

§ fopen() 예제– 파일에 자료를 읽고 쓰기를 위해서 파일을 준비 시킬 때

– my_file.txt을읽기 쓰기가 모두 가능한 모드로 준비 함– 만약 my_file.txt이 없으면 NULL이 반환– 만약 my_file.txt이 있으면 open되고, my_file.txt 안에 있는내용은 모두 유지됨

– 읽기나 쓰기의 시작점은 파일의 맨 처음 위치임

FILE *fp ;fp = fopen(“my_file.txt”, “r+”);

Page 9: 14. fiile io

9

File Operation Function fopen()

§ fopen() 예제– 파일에 자료를 읽고 쓰기를 위해서 파일을 준비 시킬 때

– my_file.txt을읽기 쓰기가 모두 가능한 모드로 준비 함– 만약 my_file.txt이 없으면 my_file.txt가 생성됨– 만약 my_file.txt이 있으면 open되면서, my_file.txt 안에 있는내용은 모두 지워짐

FILE *fp ;fp = fopen(“my_file.txt”, “w+”);

Page 10: 14. fiile io

10

File Operation Function fopen()

§ fopen() 예제– 파일에 자료를 읽고 쓰기를 위해서 파일을 준비 시킬 때

– my_file.txt을읽기 쓰기가 모두 가능한 모드로 준비 함– 만약 my_file.txt이 없으면 my_file.txt가 생성됨– 만약 my_file.txt이 있으면 open되고, my_file.txt 안에 있는내용은 모두 유지됨

– 읽기나 쓰기의 시작점은 파일의 맨 마지막임

FILE *fp ;fp = fopen(“my_file.txt”, “a+”);

Page 11: 14. fiile io

11

File pointer

§ File pointer– File I/O는 disk file명이 아닌 file pointer를 통해 stream을 생

성하여 수행.

§ ‘FILE’ Typestdio.h file에서 typedef로 정의된 type으로 file에 대한 여러정보를수록한 struct type

[Ex]FILE *fp; /* file pointer로 ‘fp’ 선언*/

Page 12: 14. fiile io

12

File Operation Function fclose()

§ fclose()– fopen으로 open한파일의 사용이 끝나면 fclose를써서 반드시 파일을 닫아야 함.

§ fclose() Syntax

int fclose( FILE *stream );

open했던 file pointer name

Returns 0 : successfulEOF : error

(EOF is defined as –1 in stdio.h)

Page 13: 14. fiile io

13

File Operation Function fopen()

§ fclose() 예제#include <stdio.h>

int main() {FILE *fp ;fp = fopen(“my_file.txt”, “r”);

...

fclose( fp ) ;

return 0}

Page 14: 14. fiile io

14

Formatted I/O Function fprintf()

§ fprintf()– 파일 처리를 위한 printf()문이다.

– 첫 인자는 fopen에의해서 쓰기 가능한 모드로 open된파일포인터이다

– 그 외는 printf와 동일하다– fprintf에 의해서 출력된 결과는 abc.txt 안에 기록된다.

FILE* fp = fopen( “abc.txt”, “w” ) ;fprintf( fp, “%d %d\n”, 1, 2 );

Page 15: 14. fiile io

15

Formatted I/O Function fprintf()

§ fscanf()– 파일 처리를 위한 scanf()문이다.

– 첫 인자는 fopen에의해서 읽기 가능한 모드로 open된파일포인터이다

– 그 외는 scanf와동일하다– abc.txt 내용이 scanf에의해서 프로그램 내로 읽어들여진다

int i, j ;FILE* fp = fopen( “abc.txt”, “r” ) ;fscanf( fp, “%d %d”, &i, &j );

Page 16: 14. fiile io

16

feof() Function

§ feof()– 현재의 file pointer가 file의 끝까지 다 읽었는지를알아보는함수

int feof( FILE *stream );

open했던 file pointer name

Returns none-zero : EOF일 경우0 : EOF가 아닐 경우

Page 17: 14. fiile io

17

Formatted I/O Function fprintf() and fscanf()

#include <stdio.h>

int main() {int i, j, k ;FILE *ifp, *ofp ;ifp = fopen("abc.txt", "r" ) ;ofp = fopen("cal.txt", "w" ) ;fscanf( ifp, "%d %d %d", &i, &j, &k ) ;fprintf( ofp, "sum: %d\n", i + j + k ) ;fclose( ifp ) ;fclose( ofp ) ;return 0 ;

}

§ fprintf(), fscanf() 예제1 2 3

abc.txt

cal.txt는없음

Page 18: 14. fiile io

18

Formatted I/O Function fprintf() and fscanf()

#include <stdio.h>

int main() {int i, j, k ;FILE *ifp, *ofp ;ifp = fopen("abc.txt", "r" ) ;ofp = fopen("cal.txt", "w" ) ;fscanf( ifp, "%d %d %d", &i, &j, &k ) ;fprintf( ofp, "sum: %d\n", i + j + k ) ;fclose( ifp ) ;fclose( ofp ) ;

return 0 ;}

§ fprintf(), fscanf() 예제1 2 3

abc.txt

This is a file.

cal.txt

Page 19: 14. fiile io

19

Formatted I/O Function fprintf() and fscanf()

#include <stdio.h>

int main() {int i, j, k ;FILE *ifp, *ofp ;ifp = fopen("abc.txt", "r" ) ;ofp = fopen("cal.txt", "a" ) ;fscanf( ifp, "%d %d %d", &i, &j, &k ) ;fprintf( ofp, "sum: %d\n", i + j + k ) ;fclose( ifp ) ;fclose( ofp ) ;

return 0;}

§ fprintf(), fscanf() 예제1 2 3

abc.txt

This is a file.

cal.txt

Page 20: 14. fiile io

20

Formatted I/O Function fprintf() and fscanf()

#include <stdio.h>

int main() {char c ;FILE *ifp, *ofp ;ifp = fopen("abc.txt", "r" ) ;ofp = fopen("abc2.txt", "a" ) ;while( feof(ifp) == 0 ) {

fscanf( ifp, "%c", &c ) ;fprintf( ofp, "%c", c ) ;

}fclose( ifp ) ;fclose( ofp ) ;return 0;

}

§ fprintf(), fscanf() 예제This is afile.1 2 3

abc.txt

Page 21: 14. fiile io

21

기타파일입출력함수§ fgetc() , getc()

– file로 부터 문자를 읽는 함수. • 만약 더 이상 읽을 문자가 없으면 EOF를 반환

– fgetc와 getc는 동일하다.

char c ;FILE *fp = fopen("abc.txt", "r" ) ;

while( (c = fgetc(fp)) != EOF )printf("%c", c ) ;

int fgetc ( FILE *stream ) ;

Page 22: 14. fiile io

22

기타파일입출력함수§ fputc() , putc()

– File에 한 문자를 쓰는 함수. – fputc와 putc는 동일하다.

char c ;FILE *fp = fopen("abc.txt", "r" ) ;FILE *ofp = fopen("xyz.txt", "w" ) ;

while( (c = fgetc(fp)) != EOF )fputc( c, ofp ) ;

int fputc ( int c, FILE *stream ) ;

Page 23: 14. fiile io

23

기타파일입출력함수§ fputs() : Writing a string

– 파일에 대한 puts이다.

– NULL 부분 전까지 파일로 복사된다.– 호출이 성공하면 음수가 아닌 값을 리턴한다.– 호출이 실패하면 EOF를 리턴한다.

int fputs(char *str, FILE *fp);

Page 24: 14. fiile io

24

기타파일입출력함수FILE *fp;int i;char *data[3]={"to be\n","or not\n","to be\n"};

fp = fopen("abc.txt", "w");

for(i = 0; i<3; i++) fputs(data[i],fp);

fclose( fp );

Page 25: 14. fiile io

25

기타파일입출력함수§ fgets() : Reading a String

– 파일에 대한 gets

– fp가 지정하는 파일에서 최대 num – 1개의 문자를 읽어 str이포인트하는 배열에 저장한다.

– ‘\n’이나 EOF를 만나면 읽기를 중단하고 NULL을 저장한다.– 읽기가 성공하면 str을 리턴하고 그렇지 않으면 NULL을 리턴한다.

char *fgets(char *str, int num, FILE *fp);

Page 26: 14. fiile io

26

기타파일입출력함수§ fgets()

char s[5] ;FILE* fp = fopen("abc.txt", "r" ) ;fgets( s, 5, fp ) ;

1231 21234567

Page 27: 14. fiile io

27

기타파일입출력함수§ gets함수와 fgets함수의차이

– gets함수 : ‘\n’가 나오기까지 읽음. 그러나 ‘\n’는 저장 안됨

– fgets함수 : ‘\n’가 나오기까지 읽음. ‘\n’도 저장 됨

Page 28: 14. fiile io

28

Accessing a File Randomly

§ 파일을한번읽고서다시읽고싶으면?

char c ;FILE *fp = fopen("abc.txt", "r" ) ;

while( !foef(fp) ) {fscanf( fp, "%c", &c ) ;printf("%c", c ) ;

}

while( !foef(fp) ) {fscanf( fp, "%c", &c ) ;printf("%c", c ) ;

}

abcdefghi

abc.txt

Page 29: 14. fiile io

29

Accessing a File Randomly

§ rewind()

– 파일 포인터를 맨처음으로 옮긴다.

void rewind( FILE* ) ;

char c ;FILE *fp = fopen("abc.txt", “r” ) ;

while( !foef(fp) ) {fscanf( fp, "%c", &c ) ;printf("%c", c ) ;

}rewind( fp ) ;while( !foef(fp) ) {

fscanf( fp, "%c", &c ) ;printf("%c", c ) ;

}

abcdefghi

abc.txt

Page 30: 14. fiile io

30

Accessing a File Randomly

§ fseek()

– place에서 offset만큼떨어진 위치에 file position indicator를둔다.

– place의 값은 0 (파일의 맨처음 ), 1 (현재위치), 2(맨끝)의값을 갖는다.

fseek( file_ptr, offset, place);

Page 31: 14. fiile io

31

Accessing a File Randomly

§ fseek()

fseek( file_ptr, offset, place);

0 (파일의 맨처음 )1 (현재위치)2(맨끝)

0123456789abcdefghjk

abc.txt

Page 32: 14. fiile io

32

Accessing a File Randomly

§ ftell()

– file position indicator의 현재 값을 return한다.– return된 값은 처음을 0으로 두고 처음부터몇 byte 떨어져있는가의 값을 나타낸다.

– 파일로부터한 문자씩 읽을 때 마다 indicator의 값을 1증가시킨다.

int ftell( FILE* );

Page 33: 14. fiile io

33

Accessing a File Randomly

§ ftell()

char c ;int pos ;FILE *fp = fopen("abc.txt", “r” ) ;

while( !foef(fp) ) {fscanf( fp, "%c", &c ) ;printf("%d: %c\n", ftell(fp), c ) ;

}

abcdefghi

abc.txt

Page 34: 14. fiile io

34

stdin, stdout & stderr

§ fprintf를사용해서화면에출력하기

– stdout은화면을 의미하는 파일 포인터임.

§ fscanf를사용해서키보드에서읽기

– stdin은 키보드를 의미하는파일 포인터임.

printf( “This is a test\n” ) ; fprintf( stdout, “This is a test\n” ) ;

scanf( “%d”, &k ) ; fscanf( stdin, “%d”, &k ) ;

Page 35: 14. fiile io

35

stdin, stdout & stderr

Standard C files in stdio.h

Written in C Name Remark

stdin standard input file connected to the keyboard

stdout standard output file connected to the screen

stderr standard error file connected to the screen

§ stdio.h에있는 3가지 file pointer

Page 36: 14. fiile io

36

stdin, stdout & stderr

#include <stdio.h>

int main() {int k, j ;fscanf( stdin, "%d %d", &k, &j ) ;fprintf( stdout, "Sum: %d\n", k + j ) ;fprintf( stderr, "OK\n") ;

return 0 ;}