SlideShare ist ein Scribd-Unternehmen logo
1 von 36
Downloaden Sie, um offline zu lesen
File I/O
2
File 입출력
§ 지금까지의 프로그램 입출력
– 입력: Keyboard
– 출력: Monitor
§ 필요한 자료를 파일에서 읽어서 출력을 파일로 할 수
없을까?
국 영 수
1 80 90 70
2 80 60 40
3 60 50 70
…
C program
국 영 수 평균
1 80 90 70 80
2 80 60 40 60
3 60 50 70 60
…
3
File 입출력
§ 파일을 이용한 입출력 절차
해당 파일 열기
파일에서 읽기
파일에 쓰기
파일 닫기
fopen
fscanf, fprintf, fgets, fputs, …
fclose
4
File Operation Function fopen()
§ fopen()
– 외부 file을 프로그램에서 사용하기 위해 준비시키는 명령
– 입력에 이용될 모든 파일은 fopen을 통하여 준비되어야 함
– Return값: FILE 구조체의 pointer
• 파일에 대한 읽기 혹은 쓰기는 fopen이 반환한 FILE pointer를
통해서 이루어짐
§ fopen() Syntax
FILE *fopen( const char *filename, const char *mode );
file pointer로 return disk에 있는 filename file open시의 mode
5
File Operation Function fopen()
§ fopen() 예제
– 파일에서 자료를 읽기 위해서 파일을 준비 시킬 때
– my_file.txt을 읽기모드로 준비 함
– 만약 파일이 없으면 NULL이 반환됨
FILE *fp ;
fp = fopen(“my_file.txt”, “r”);
6
File Operation Function fopen()
§ fopen() 예제
– 파일에 자료를 쓰기 위해서 파일을 준비 시킬 때
– my_file.txt를 쓰기모드로 준비시킴
– 만약 파일이 없으면 my_file.txt이 생성됨
– 만약 이미 my_file.txt가 존재하면, 그 안에 있는 모든 내용이
지워짐
FILE *fp ;
fp = fopen(“my_file.txt”, “w”);
7
File Operation Function fopen()
§ fopen() 예제
– 파일에 자료를 추가로 쓰기 위해서 파일을 준비 시킬 때
– my_file.txt를 append모드로 준비시킴
– 만약 파일이 없으면 my_file.txt이 생성됨
– 만약 이미 my_file.txt가 존재하면, 기존의 내용은 그대로 유
지되고 새로 쓰여지는 것은 파일 마지막에 추가됨
FILE *fp ;
fp = fopen(“my_file.txt”, “a”);
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+”);
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+”);
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+”);
11
File pointer
§ File pointer
– File I/O는 disk file명이 아닌 file pointer를 통해 stream을 생
성하여 수행.
§ ‘FILE’ Type
stdio.h file에서 typedef로 정의된 type으로 file에 대한 여러
정보를 수록한 struct type
[Ex]
FILE *fp; /* file pointer로 ‘fp’ 선언
*/
12
File Operation Function fclose()
§ fclose()
– fopen으로 open한 파일의 사용이 끝나면 fclose를 써서 반드
시 파일을 닫아야 함.
§ fclose() Syntax
int fclose( FILE *stream );
open했던 file pointer name
Returns 0 : successful
EOF : error
(EOF is defined as –1 in stdio.h)
13
File Operation Function fopen()
§ fclose() 예제
#include <stdio.h>
int main() {
FILE *fp ;
fp = fopen(“my_file.txt”, “r”);
...
fclose( fp ) ;
return 0
}
14
Formatted I/O Function fprintf()
§ fprintf()
– 파일 처리를 위한 printf()문이다.
– 첫 인자는 fopen에 의해서 쓰기 가능한 모드로 open된 파일
포인터이다
– 그 외는 printf와 동일하다
– fprintf에 의해서 출력된 결과는 abc.txt 안에 기록된다.
FILE* fp = fopen( “abc.txt”, “w” ) ;
fprintf( fp, “%d %dn”, 1, 2 );
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 );
16
feof() Function
§ feof()
– 현재의 file pointer가 file의 끝까지 다 읽었는지를 알아보는
함수
int feof( FILE *stream );
open했던 file pointer name
Returns none-zero : EOF일 경우
0 : EOF가 아닐 경우
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: %dn", i + j + k ) ;
fclose( ifp ) ;
fclose( ofp ) ;
return 0 ;
}
§ fprintf(), fscanf() 예제
1 2 3
abc.txt
cal.txt는 없음
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: %dn", i + j + k ) ;
fclose( ifp ) ;
fclose( ofp ) ;
return 0 ;
}
§ fprintf(), fscanf() 예제
1 2 3
abc.txt
This is a
file.
cal.txt
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: %dn", i + j + k ) ;
fclose( ifp ) ;
fclose( ofp ) ;
return 0;
}
§ fprintf(), fscanf() 예제
1 2 3
abc.txt
This is a
file.
cal.txt
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 a
file.
1 2 3
abc.txt
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 ) ;
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 ) ;
23
기타 파일 입출력 함수
§ fputs() : Writing a string
– 파일에 대한 puts이다.
– NULL 부분 전까지 파일로 복사된다.
– 호출이 성공하면 음수가 아닌 값을 리턴한다.
– 호출이 실패하면 EOF를 리턴한다.
int fputs(char *str, FILE *fp);
24
기타 파일 입출력 함수
FILE *fp;
int i;
char *data[3]={"to ben","or notn","to ben"};
fp = fopen("abc.txt", "w");
for(i = 0; i<3; i++) fputs(data[i],fp);
fclose( fp );
25
기타 파일 입출력 함수
§ fgets() : Reading a String
– 파일에 대한 gets
– fp가 지정하는 파일에서 최대 num – 1개의 문자를 읽어 str이
포인트하는 배열에 저장한다.
– ‘n’이나 EOF를 만나면 읽기를 중단하고 NULL을 저장한다.
– 읽기가 성공하면 str을 리턴하고 그렇지 않으면 NULL을 리턴
한다.
char *fgets(char *str, int num, FILE *fp);
26
기타 파일 입출력 함수
§ fgets()
char s[5] ;
FILE* fp = fopen("abc.txt", "r" ) ;
fgets( s, 5, fp ) ;
123
1 2
1234567
27
기타 파일 입출력 함수
§ gets함수와 fgets함수의 차이
– gets함수 : ‘n’가 나오기까지 읽음. 그러나 ‘n’는 저장 안됨
– fgets함수 : ‘n’가 나오기까지 읽음. ‘n’도 저장 됨
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 ) ;
}
abcd
efghi
abc.txt
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 ) ;
}
abcd
efghi
abc.txt
30
Accessing a File Randomly
§ fseek()
– place에서 offset만큼 떨어진 위치에 file position indicator를
둔다.
– place의 값은 0 (파일의 맨처음 ), 1 (현재위치), 2(맨끝)의 값
을 갖는다.
fseek( file_ptr, offset, place);
31
Accessing a File Randomly
§ fseek()
fseek( file_ptr, offset, place);
0 (파일의 맨처음 )
1 (현재위치)
2(맨끝)
0123456789
abcdefghjk
abc.txt
32
Accessing a File Randomly
§ ftell()
– file position indicator의 현재 값을 return한다.
– return된 값은 처음을 0으로 두고 처음부터 몇 byte 떨어져
있는가의 값을 나타낸다.
– 파일로부터 한 문자씩 읽을 때 마다 indicator의 값을 1증가
시킨다.
int ftell( FILE* );
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: %cn", ftell(fp), c ) ;
}
abcd
efghi
abc.txt
34
stdin, stdout & stderr
§ fprintf를 사용해서 화면에 출력하기
– stdout은 화면을 의미하는 파일 포인터임.
§ fscanf를 사용해서 키보드에서 읽기
– stdin은 키보드를 의미하는 파일 포인터임.
printf( “This is a testn” ) ; fprintf( stdout, “This is a testn” ) ;
scanf( “%d”, &k ) ; fscanf( stdin, “%d”, &k ) ;
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
36
stdin, stdout & stderr
#include <stdio.h>
int main() {
int k, j ;
fscanf( stdin, "%d %d", &k, &j ) ;
fprintf( stdout, "Sum: %dn", k + j ) ;
fprintf( stderr, "OKn") ;
return 0 ;
}

Weitere ähnliche Inhalte

Was ist angesagt?

10장 문자열클래스와파일클래스
10장 문자열클래스와파일클래스10장 문자열클래스와파일클래스
10장 문자열클래스와파일클래스웅식 전
 
[강릉원주대 대기환경과학과] 대기과학전산입문 설명서
[강릉원주대 대기환경과학과] 대기과학전산입문 설명서[강릉원주대 대기환경과학과] 대기과학전산입문 설명서
[강릉원주대 대기환경과학과] 대기과학전산입문 설명서Lee Sang-Ho
 
Learning Node Book, Chapter 5
Learning Node Book, Chapter 5Learning Node Book, Chapter 5
Learning Node Book, Chapter 5Ji Hun Kim
 
파으리떤Pt 사냥
파으리떤Pt 사냥파으리떤Pt 사냥
파으리떤Pt 사냥Seonyoung Lee
 
Function calling convention
Function calling conventionFunction calling convention
Function calling conventionYuk SeungChan
 
파이썬2.7 기초 공부한 것 정리
파이썬2.7 기초 공부한 것 정리파이썬2.7 기초 공부한 것 정리
파이썬2.7 기초 공부한 것 정리Booseol Shin
 
고급시스템프로그래밍
고급시스템프로그래밍고급시스템프로그래밍
고급시스템프로그래밍kimkiweon
 
자료구조 Project3
자료구조 Project3자료구조 Project3
자료구조 Project3KoChungWook
 
Perl Script Document
Perl Script DocumentPerl Script Document
Perl Script Document오석 한
 
3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib웅식 전
 
Javascript개발자의 눈으로 python 들여다보기
Javascript개발자의 눈으로 python 들여다보기Javascript개발자의 눈으로 python 들여다보기
Javascript개발자의 눈으로 python 들여다보기지수 윤
 
자초스북스터디 20170610 go_3_4
자초스북스터디 20170610 go_3_4자초스북스터디 20170610 go_3_4
자초스북스터디 20170610 go_3_4동규 이
 
Dependency hell과 빌드지옥 탈출
Dependency hell과 빌드지옥 탈출Dependency hell과 빌드지옥 탈출
Dependency hell과 빌드지옥 탈출Byeongsu Kang
 
Python3 brief summary
Python3 brief summaryPython3 brief summary
Python3 brief summaryHoChul Shin
 
PINTOS Operating system homework
PINTOS Operating system homeworkPINTOS Operating system homework
PINTOS Operating system homeworkGichan Lee
 
Kgc2006 Template Metaprogramming을 이용한 LuaTinker 구현
Kgc2006 Template Metaprogramming을 이용한 LuaTinker 구현Kgc2006 Template Metaprogramming을 이용한 LuaTinker 구현
Kgc2006 Template Metaprogramming을 이용한 LuaTinker 구현Sang Goo Kwon
 
PINTOS Operating system homework 2
PINTOS Operating system homework 2PINTOS Operating system homework 2
PINTOS Operating system homework 2Gichan Lee
 

Was ist angesagt? (20)

10장 문자열클래스와파일클래스
10장 문자열클래스와파일클래스10장 문자열클래스와파일클래스
10장 문자열클래스와파일클래스
 
[강릉원주대 대기환경과학과] 대기과학전산입문 설명서
[강릉원주대 대기환경과학과] 대기과학전산입문 설명서[강릉원주대 대기환경과학과] 대기과학전산입문 설명서
[강릉원주대 대기환경과학과] 대기과학전산입문 설명서
 
Learning Node Book, Chapter 5
Learning Node Book, Chapter 5Learning Node Book, Chapter 5
Learning Node Book, Chapter 5
 
파으리떤Pt 사냥
파으리떤Pt 사냥파으리떤Pt 사냥
파으리떤Pt 사냥
 
Function calling convention
Function calling conventionFunction calling convention
Function calling convention
 
Stack frame
Stack frameStack frame
Stack frame
 
파이썬2.7 기초 공부한 것 정리
파이썬2.7 기초 공부한 것 정리파이썬2.7 기초 공부한 것 정리
파이썬2.7 기초 공부한 것 정리
 
고급시스템프로그래밍
고급시스템프로그래밍고급시스템프로그래밍
고급시스템프로그래밍
 
자료구조 Project3
자료구조 Project3자료구조 Project3
자료구조 Project3
 
Perl Script Document
Perl Script DocumentPerl Script Document
Perl Script Document
 
3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib
 
Javascript개발자의 눈으로 python 들여다보기
Javascript개발자의 눈으로 python 들여다보기Javascript개발자의 눈으로 python 들여다보기
Javascript개발자의 눈으로 python 들여다보기
 
자초스북스터디 20170610 go_3_4
자초스북스터디 20170610 go_3_4자초스북스터디 20170610 go_3_4
자초스북스터디 20170610 go_3_4
 
Dependency hell과 빌드지옥 탈출
Dependency hell과 빌드지옥 탈출Dependency hell과 빌드지옥 탈출
Dependency hell과 빌드지옥 탈출
 
3. linked list
3. linked list3. linked list
3. linked list
 
Python3 brief summary
Python3 brief summaryPython3 brief summary
Python3 brief summary
 
파이선 실전공략-1
파이선 실전공략-1파이선 실전공략-1
파이선 실전공략-1
 
PINTOS Operating system homework
PINTOS Operating system homeworkPINTOS Operating system homework
PINTOS Operating system homework
 
Kgc2006 Template Metaprogramming을 이용한 LuaTinker 구현
Kgc2006 Template Metaprogramming을 이용한 LuaTinker 구현Kgc2006 Template Metaprogramming을 이용한 LuaTinker 구현
Kgc2006 Template Metaprogramming을 이용한 LuaTinker 구현
 
PINTOS Operating system homework 2
PINTOS Operating system homework 2PINTOS Operating system homework 2
PINTOS Operating system homework 2
 

Andere mochten auch

Andere mochten auch (8)

15 2. arguement passing to main
15 2. arguement passing to main15 2. arguement passing to main
15 2. arguement passing to main
 
15 3. modulization
15 3. modulization15 3. modulization
15 3. modulization
 
9. pointer, pointer & function
9. pointer, pointer & function9. pointer, pointer & function
9. pointer, pointer & function
 
15 3. modulization
15 3. modulization15 3. modulization
15 3. modulization
 
Function pointer
Function pointerFunction pointer
Function pointer
 
13. structure
13. structure13. structure
13. structure
 
Data structure lecture 1
Data structure   lecture 1Data structure   lecture 1
Data structure lecture 1
 
Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
 

Mehr von 웅식 전

12 2. dynamic allocation
12 2. dynamic allocation12 2. dynamic allocation
12 2. dynamic allocation웅식 전
 
12 1. multi-dimensional array
12 1. multi-dimensional array12 1. multi-dimensional array
12 1. multi-dimensional array웅식 전
 
11. array & pointer
11. array & pointer11. array & pointer
11. array & pointer웅식 전
 
10. pointer & function
10. pointer & function10. pointer & function
10. pointer & function웅식 전
 
7. variable scope rule,-storage_class
7. variable scope rule,-storage_class7. variable scope rule,-storage_class
7. variable scope rule,-storage_class웅식 전
 
5 2. string processing
5 2. string processing5 2. string processing
5 2. string processing웅식 전
 
5 1. character processing
5 1. character processing5 1. character processing
5 1. character processing웅식 전
 
15 1. enumeration, typedef
15 1. enumeration, typedef15 1. enumeration, typedef
15 1. enumeration, typedef웅식 전
 
3 2. if statement
3 2. if statement3 2. if statement
3 2. if statement웅식 전
 
2 3. standard io
2 3. standard io2 3. standard io
2 3. standard io웅식 전
 
2 2. operators
2 2. operators2 2. operators
2 2. operators웅식 전
 
2 1. variables & data types
2 1. variables & data types2 1. variables & data types
2 1. variables & data types웅식 전
 
Goorm ide 교육용버전 for skku(학생)
Goorm ide 교육용버전 for skku(학생)Goorm ide 교육용버전 for skku(학생)
Goorm ide 교육용버전 for skku(학생)웅식 전
 
구름 기본 소개자료
구름 기본 소개자료구름 기본 소개자료
구름 기본 소개자료웅식 전
 
Goorm ide 소개 슬라이드(교육용 버전)
Goorm ide 소개 슬라이드(교육용 버전)Goorm ide 소개 슬라이드(교육용 버전)
Goorm ide 소개 슬라이드(교육용 버전)웅식 전
 
13th chapter12 slide
13th chapter12 slide13th chapter12 slide
13th chapter12 slide웅식 전
 

Mehr von 웅식 전 (20)

12 2. dynamic allocation
12 2. dynamic allocation12 2. dynamic allocation
12 2. dynamic allocation
 
12 1. multi-dimensional array
12 1. multi-dimensional array12 1. multi-dimensional array
12 1. multi-dimensional array
 
11. array & pointer
11. array & pointer11. array & pointer
11. array & pointer
 
10. pointer & function
10. pointer & function10. pointer & function
10. pointer & function
 
9. pointer
9. pointer9. pointer
9. pointer
 
7. variable scope rule,-storage_class
7. variable scope rule,-storage_class7. variable scope rule,-storage_class
7. variable scope rule,-storage_class
 
6. function
6. function6. function
6. function
 
5 2. string processing
5 2. string processing5 2. string processing
5 2. string processing
 
5 1. character processing
5 1. character processing5 1. character processing
5 1. character processing
 
15 1. enumeration, typedef
15 1. enumeration, typedef15 1. enumeration, typedef
15 1. enumeration, typedef
 
4. loop
4. loop4. loop
4. loop
 
3 2. if statement
3 2. if statement3 2. if statement
3 2. if statement
 
2 3. standard io
2 3. standard io2 3. standard io
2 3. standard io
 
2 2. operators
2 2. operators2 2. operators
2 2. operators
 
2 1. variables & data types
2 1. variables & data types2 1. variables & data types
2 1. variables & data types
 
Goorm ide 교육용버전 for skku(학생)
Goorm ide 교육용버전 for skku(학생)Goorm ide 교육용버전 for skku(학생)
Goorm ide 교육용버전 for skku(학생)
 
구름 기본 소개자료
구름 기본 소개자료구름 기본 소개자료
구름 기본 소개자료
 
Goorm ide 소개 슬라이드(교육용 버전)
Goorm ide 소개 슬라이드(교육용 버전)Goorm ide 소개 슬라이드(교육용 버전)
Goorm ide 소개 슬라이드(교육용 버전)
 
W14 chap13
W14 chap13W14 chap13
W14 chap13
 
13th chapter12 slide
13th chapter12 slide13th chapter12 slide
13th chapter12 slide
 

14. fiile io

  • 2. 2 File 입출력 § 지금까지의 프로그램 입출력 – 입력: Keyboard – 출력: Monitor § 필요한 자료를 파일에서 읽어서 출력을 파일로 할 수 없을까? 국 영 수 1 80 90 70 2 80 60 40 3 60 50 70 … C program 국 영 수 평균 1 80 90 70 80 2 80 60 40 60 3 60 50 70 60 …
  • 3. 3 File 입출력 § 파일을 이용한 입출력 절차 해당 파일 열기 파일에서 읽기 파일에 쓰기 파일 닫기 fopen fscanf, fprintf, fgets, fputs, … fclose
  • 4. 4 File Operation Function fopen() § fopen() – 외부 file을 프로그램에서 사용하기 위해 준비시키는 명령 – 입력에 이용될 모든 파일은 fopen을 통하여 준비되어야 함 – Return값: FILE 구조체의 pointer • 파일에 대한 읽기 혹은 쓰기는 fopen이 반환한 FILE pointer를 통해서 이루어짐 § fopen() Syntax FILE *fopen( const char *filename, const char *mode ); file pointer로 return disk에 있는 filename file open시의 mode
  • 5. 5 File Operation Function fopen() § fopen() 예제 – 파일에서 자료를 읽기 위해서 파일을 준비 시킬 때 – my_file.txt을 읽기모드로 준비 함 – 만약 파일이 없으면 NULL이 반환됨 FILE *fp ; fp = fopen(“my_file.txt”, “r”);
  • 6. 6 File Operation Function fopen() § fopen() 예제 – 파일에 자료를 쓰기 위해서 파일을 준비 시킬 때 – my_file.txt를 쓰기모드로 준비시킴 – 만약 파일이 없으면 my_file.txt이 생성됨 – 만약 이미 my_file.txt가 존재하면, 그 안에 있는 모든 내용이 지워짐 FILE *fp ; fp = fopen(“my_file.txt”, “w”);
  • 7. 7 File Operation Function fopen() § fopen() 예제 – 파일에 자료를 추가로 쓰기 위해서 파일을 준비 시킬 때 – my_file.txt를 append모드로 준비시킴 – 만약 파일이 없으면 my_file.txt이 생성됨 – 만약 이미 my_file.txt가 존재하면, 기존의 내용은 그대로 유 지되고 새로 쓰여지는 것은 파일 마지막에 추가됨 FILE *fp ; fp = fopen(“my_file.txt”, “a”);
  • 8. 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+”);
  • 9. 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+”);
  • 10. 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+”);
  • 11. 11 File pointer § File pointer – File I/O는 disk file명이 아닌 file pointer를 통해 stream을 생 성하여 수행. § ‘FILE’ Type stdio.h file에서 typedef로 정의된 type으로 file에 대한 여러 정보를 수록한 struct type [Ex] FILE *fp; /* file pointer로 ‘fp’ 선언 */
  • 12. 12 File Operation Function fclose() § fclose() – fopen으로 open한 파일의 사용이 끝나면 fclose를 써서 반드 시 파일을 닫아야 함. § fclose() Syntax int fclose( FILE *stream ); open했던 file pointer name Returns 0 : successful EOF : error (EOF is defined as –1 in stdio.h)
  • 13. 13 File Operation Function fopen() § fclose() 예제 #include <stdio.h> int main() { FILE *fp ; fp = fopen(“my_file.txt”, “r”); ... fclose( fp ) ; return 0 }
  • 14. 14 Formatted I/O Function fprintf() § fprintf() – 파일 처리를 위한 printf()문이다. – 첫 인자는 fopen에 의해서 쓰기 가능한 모드로 open된 파일 포인터이다 – 그 외는 printf와 동일하다 – fprintf에 의해서 출력된 결과는 abc.txt 안에 기록된다. FILE* fp = fopen( “abc.txt”, “w” ) ; fprintf( fp, “%d %dn”, 1, 2 );
  • 15. 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 );
  • 16. 16 feof() Function § feof() – 현재의 file pointer가 file의 끝까지 다 읽었는지를 알아보는 함수 int feof( FILE *stream ); open했던 file pointer name Returns none-zero : EOF일 경우 0 : EOF가 아닐 경우
  • 17. 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: %dn", i + j + k ) ; fclose( ifp ) ; fclose( ofp ) ; return 0 ; } § fprintf(), fscanf() 예제 1 2 3 abc.txt cal.txt는 없음
  • 18. 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: %dn", i + j + k ) ; fclose( ifp ) ; fclose( ofp ) ; return 0 ; } § fprintf(), fscanf() 예제 1 2 3 abc.txt This is a file. cal.txt
  • 19. 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: %dn", i + j + k ) ; fclose( ifp ) ; fclose( ofp ) ; return 0; } § fprintf(), fscanf() 예제 1 2 3 abc.txt This is a file. cal.txt
  • 20. 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 a file. 1 2 3 abc.txt
  • 21. 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 ) ;
  • 22. 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 ) ;
  • 23. 23 기타 파일 입출력 함수 § fputs() : Writing a string – 파일에 대한 puts이다. – NULL 부분 전까지 파일로 복사된다. – 호출이 성공하면 음수가 아닌 값을 리턴한다. – 호출이 실패하면 EOF를 리턴한다. int fputs(char *str, FILE *fp);
  • 24. 24 기타 파일 입출력 함수 FILE *fp; int i; char *data[3]={"to ben","or notn","to ben"}; fp = fopen("abc.txt", "w"); for(i = 0; i<3; i++) fputs(data[i],fp); fclose( fp );
  • 25. 25 기타 파일 입출력 함수 § fgets() : Reading a String – 파일에 대한 gets – fp가 지정하는 파일에서 최대 num – 1개의 문자를 읽어 str이 포인트하는 배열에 저장한다. – ‘n’이나 EOF를 만나면 읽기를 중단하고 NULL을 저장한다. – 읽기가 성공하면 str을 리턴하고 그렇지 않으면 NULL을 리턴 한다. char *fgets(char *str, int num, FILE *fp);
  • 26. 26 기타 파일 입출력 함수 § fgets() char s[5] ; FILE* fp = fopen("abc.txt", "r" ) ; fgets( s, 5, fp ) ; 123 1 2 1234567
  • 27. 27 기타 파일 입출력 함수 § gets함수와 fgets함수의 차이 – gets함수 : ‘n’가 나오기까지 읽음. 그러나 ‘n’는 저장 안됨 – fgets함수 : ‘n’가 나오기까지 읽음. ‘n’도 저장 됨
  • 28. 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 ) ; } abcd efghi abc.txt
  • 29. 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 ) ; } abcd efghi abc.txt
  • 30. 30 Accessing a File Randomly § fseek() – place에서 offset만큼 떨어진 위치에 file position indicator를 둔다. – place의 값은 0 (파일의 맨처음 ), 1 (현재위치), 2(맨끝)의 값 을 갖는다. fseek( file_ptr, offset, place);
  • 31. 31 Accessing a File Randomly § fseek() fseek( file_ptr, offset, place); 0 (파일의 맨처음 ) 1 (현재위치) 2(맨끝) 0123456789 abcdefghjk abc.txt
  • 32. 32 Accessing a File Randomly § ftell() – file position indicator의 현재 값을 return한다. – return된 값은 처음을 0으로 두고 처음부터 몇 byte 떨어져 있는가의 값을 나타낸다. – 파일로부터 한 문자씩 읽을 때 마다 indicator의 값을 1증가 시킨다. int ftell( FILE* );
  • 33. 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: %cn", ftell(fp), c ) ; } abcd efghi abc.txt
  • 34. 34 stdin, stdout & stderr § fprintf를 사용해서 화면에 출력하기 – stdout은 화면을 의미하는 파일 포인터임. § fscanf를 사용해서 키보드에서 읽기 – stdin은 키보드를 의미하는 파일 포인터임. printf( “This is a testn” ) ; fprintf( stdout, “This is a testn” ) ; scanf( “%d”, &k ) ; fscanf( stdin, “%d”, &k ) ;
  • 35. 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
  • 36. 36 stdin, stdout & stderr #include <stdio.h> int main() { int k, j ; fscanf( stdin, "%d %d", &k, &j ) ; fprintf( stdout, "Sum: %dn", k + j ) ; fprintf( stderr, "OKn") ; return 0 ; }