Chapter 13 InputOutput and Files Contents File pointer

  • Slides: 44
Download presentation
프로그래밍 기초와 실습 Chapter 13 Input/Output and Files

프로그래밍 기초와 실습 Chapter 13 Input/Output and Files

Contents § File pointer § Function feof() § File Operation Function fopen(), fclose() §

Contents § File pointer § Function feof() § File Operation Function fopen(), fclose() § Formatted I/O Function fprintf(), fscanf() § Character I/O Function getc(), putc() § Using Command Line Arguments § Double-Spacing a File Chapter 13 Input/Output and Files 2

Contents § § § § The I/O Function in stdio. h String I/O Function

Contents § § § § The I/O Function in stdio. h String I/O Function sprintf() String I/O Function sscanf() Line I/O Function fputs() Line I/O Function fgets() Using Temporary Files and Graceful Functions Accessing a File Randomly Chapter 13 Input/Output and Files 3

File pointer § File pointer – § File I/O는 disk file명이 아닌 file pointer를

File pointer § File pointer – § File I/O는 disk file명이 아닌 file pointer를 통해 stream을 생 성하여 수행. 선언 [Ex] FILE *fp; § /* file pointer로 ‘fp’ 선언 */ ‘FILE’ Type stdio. h file에서 typedef로 정의된 type으로 file에 대한 여러 정 보를 수록한 struct type Chapter 13 Input/Output and Files 4

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

feof() Function § feof() – 현재의 file pointer가 file의 끝까지 다 읽었는지를 알아보는 함수 § feof() Syntax int feof( FILE *stream ); open했던 file pointer name Chapter 13 Input/Output and Files Returns 0 : EOF일 경우 none-zero : EOF가 아닐경우 5

File Operation Function fopen() § fopen() – 외부 file을 프로그램에서 사용할 때 필요한 명령

File Operation Function fopen() § fopen() – 외부 file을 프로그램에서 사용할 때 필요한 명령 § fopen() Syntax FILE *fopen( const char *filename, const char *mode ); file pointer로 return disk에 있는 filename file open시의 mode [Ex] fp = fopen( “in. txt”, “r”); /* 읽기 전용으로 in. txt파일을 연다. */ Chapter 13 Input/Output and Files 6

File Operation Function fopen() § fopen() 의 모드 Mode Strings for Text/Binary Files String

File Operation Function fopen() § fopen() 의 모드 Mode Strings for Text/Binary Files String Meaning “r” “w” “a” “rb” “wb” “ab” “r+” “w+” “a+” “rb+” “wb+” “ab+” open text file for reading open text file for writing open text file for appending open binary file for reading open binary file for writing open binary file for appending open text file for reading and writing, starting at beginning open text file for reading and writing(truncate if file exists) open text file for reading and writing (append if file exists) open binary file for reading and writing, starting at beginning open binary file for reading and writing(truncate if file exists) open binary file for reading and writing (append if file exists) Chapter 13 Input/Output and Files 7

File Operation Function fopen() § fopen() 예제 [Ex] #include <stdio. h> int main(void) {

File Operation Function fopen() § fopen() 예제 [Ex] #include <stdio. h> int main(void) { int sum = 0; val; FILE *ifp, *ofp; ifp = fopen(“my_file”, “r”); /* open for reading */ ofp = fopen(“outfile”, ”w”); /* open for writing */ … if ( ifp == NULL || ofp == NULL ) ifp, ofp가 NULL pointer가 printf(“ Can’t open file”); 되는 경우 에러 메세지 출력 }… Chapter 13 Input/Output and Files 8

File Operation Function fclose() § fclose() – fopen으로 open한 파일의 사용이 끝나면 fclose를 써서

File Operation Function fclose() § fclose() – fopen으로 open한 파일의 사용이 끝나면 fclose를 써서 파일 을 닫을 때 필요한 명령어 § fclose() Syntax int fclose( FILE *stream ); open했던 file pointer name Chapter 13 Input/Output and Files Returns 0 : successful EOF : error (EOF is defined as – 1 in stdio. h) 9

File Operation Function fclose() § fclose() 예제 [Ex] example. dat란 파일을 #include <stdio. h>

File Operation Function fclose() § fclose() 예제 [Ex] example. dat란 파일을 #include <stdio. h> FILE_NAME로 define해서 #include <stdlib. h> 사용하는 것은 좋은 프로그래밍 #define FILE_NAME “example. dat” 습관이다. main() { FILE *fp; fp = fopen(FILE_NAME, “r”); reading가능하게 file pointer의 if ( fp == NULL ) { file을 open한다. printf(“Can’t open %sn”, FILE_NAME); exit(EXIT_FAILURE); } … fclose(fp); return 0; } Chapter 13 Input/Output and Files 10

Formatted I/O Function fprintf() § fprintf() – 파일 처리를 위한 printf()문이다. – 출력결과를 FILE

Formatted I/O Function fprintf() § fprintf() – 파일 처리를 위한 printf()문이다. – 출력결과를 FILE *fp의 파일로 보낸다. § stdio. h 파일에 있는 fprintf()의 prototype int fprintf( FILE *fp, const char *format, … ); § fprintf() Syntax fprintf( file_ptr, control_string, other_arguments ); Chapter 13 Input/Output and Files 11

Formatted I/O Function fscanf() § fscanf() – 파일 처리를 위한 scanf()문이다. – keyboard로 입력을

Formatted I/O Function fscanf() § fscanf() – 파일 처리를 위한 scanf()문이다. – keyboard로 입력을 받지 않고, 첫 번째 argument가 포인트하 는 곳으로부터 입력 받는다. – 실행에 성공하면 변환된 항목의 개수를 return한다. § stdio. h 파일에 있는 fscanf()의 prototype int fscanf( FILE *fp, const char *format, … ); § fscanf() Syntax fscanf( file_ptr, control_string, other_arguments ); Chapter 13 Input/Output and Files 12

Formatted I/O Function fprintf() and fscanf() § stdio. h에 있는 3가지 file pointer Standard

Formatted I/O Function fprintf() and fscanf() § stdio. h에 있는 3가지 file pointer 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 [Ex] fprintf(stdout, … ); fscanf(stdin, … ); connected to the screen is equivalent to Chapter 13 Input/Output and Files printf(…); scanf(…); 13

Formatted I/O Function fprintf() and fscanf() § fprintf(), fscanf() 예제 [Ex] #include <stdio. h>

Formatted I/O Function fprintf() and fscanf() § fprintf(), fscanf() 예제 [Ex] #include <stdio. h> #include <stdlib. h> #define FILE_NAME "data. txt" main() { FILE *fp; char s; FILE_NAME을 읽고 쓰기 가능한 상태로 open해서 fp로 point한다. fp = fopen(FILE_NAME, "w+"); fprintf(fp, "C Programming is Hard"); fclose(fp); data. txt 파일에 문장을 저장한 후에 fclose로 file을 닫는다. /* continue */ Chapter 13 Input/Output and Files 14

Formatted I/O Function fprintf() and fscanf() § fprintf(), fscanf() 예제 fp = fopen(FILE_NAME, "r");

Formatted I/O Function fprintf() and fscanf() § fprintf(), fscanf() 예제 fp = fopen(FILE_NAME, "r"); fscanf(fp, "%c", &s); printf("%cn", s); fclose(fp); return 0; FILE_NAME을 읽기만 가능한 상태로 open해서 fp로 point한다. fp가 point하는 file의 첫 번째 문자를 읽고 s에 저장한다. 위에서 읽은 s값을 출력한다. } C Chapter 13 Input/Output and Files 15

Character I/O Function putc() § putc() – 외부 file에 문자를 저장하는 함수. – fputc()와

Character I/O Function putc() § putc() – 외부 file에 문자를 저장하는 함수. – fputc()와 동일 § putc() Syntax int putc ( int c, FILE *stream ) ; putc가 에러없이 끝나면 c와 동일한 값을 리턴 c를 unsigned char로 변환하고, *stream이 저정하는 파일에 이것을 쓴다. [Ex] putc( c, ofp ); ofp가 포인트하는 파일에 c 값을 쓴다. Chapter 13 Input/Output and Files 17

Using Command Line Arguments § Command-Line Arguments – C program은 command line에서 argument를 program으로

Using Command Line Arguments § Command-Line Arguments – C program은 command line에서 argument를 program으로 access 가능하게 한다. § Syntax ( Example in Unix System ) [prompt ] program_name arg 1 arg 2 … arg. N 실행 가능한 file name § 사용예 [Ex] a. out file 1. txt file 2. txt Chapter 13 Input/Output and Files a. out이라는 실행파일을 실행할 때 두개의 인자로서 file 1. txt와 file 2. txt를 사용 18

Using Command Line Arguments § argv ( argument vector ) – 문자열의 배열로 생각할

Using Command Line Arguments § argv ( argument vector ) – 문자열의 배열로 생각할 수 있는 char형 포인터 배열 – argv[0]은 명령어 자체의 이름을 포함한다. argv[0] program_name argv[1] pointer to the 1 st argument : : argv[n] pointer to the nth argument § 사용예 [Ex] [prompt] a. out argv[0] Hello Handong argv[1] Chapter 13 Input/Output and Files argv[2] 20

Using Command Line Arguments § Line Arguments 예제 1 [Ex] main (int argc, char

Using Command Line Arguments § Line Arguments 예제 1 [Ex] main (int argc, char * argv[]){ int count; printf( “%sn”, argv[0] ); /* Retrieve the program_name */ if( argc > 1 ){ argument가 있다면 그 argument 모두를 출력하기 for( count = 1 ; count < argc ; count++ ) printf(“%d %sn”, count, argv[count] ); else puts( “No comand line arguments” ); } 만일 argc가 1이라면, 즉 program명으로만 command line이 구성되었다면 no command line arguments를 출력하는 code Chapter 13 Input/Output and Files 21

Using Command Line Arguments § atoi() – prototype은 stdlib. h에 있다. – 문자열 pt를

Using Command Line Arguments § atoi() – prototype은 stdlib. h에 있다. – 문자열 pt를 int로 변환하고 그것을 리턴한다. – 변환이 일어나지 않으면 0을 리턴한다. int atoi(const char * pt); § atof() – prototype은 stdlib. h에 있다. – 문자열 pt를 double로 변환하고 그것을 리턴한다. – 변환이 일어나지 않으면 0을 리턴한다. double atof(const char * pt); Chapter 13 Input/Output and Files /* Convert a string to a double */ 22

Using Command Line Arguments § +, -, x, *의 calculator program [Ex] main (int

Using Command Line Arguments § +, -, x, *의 calculator program [Ex] main (int argc, char * argv[]){ int i, s; command line의 두 번째 argumen를 check switch( * argv[i] ){ case ‘+’ : s=0; for( i = 2; i < argc ; i++) s = s + atoi(argv[i]); break; case ‘-’ : s = atoi( argv[2] ) – atoi( argv[3] ); break; case ‘*’ : for( i = 2 ; i < argc ; i++ ) s = s * atoi( argv[i] ); break; case ‘/’ : s = atoi( argv[2] ) / atoi( argv[3] ); break; } printf(“%dn”, s); 각각의 operator에 따라서 계산 } Chapter 13 Input/Output and Files 23

Using Command Line Arguments § +, -, x, *의 calculator program /* 유닉스 시스템에서

Using Command Line Arguments § +, -, x, *의 calculator program /* 유닉스 시스템에서 실행 */ [prompt] cc cal. c –o calc /* source program의 Compile */ [prompt] calc + 2 4 6 8 /*이와 같이 실행 file의 수행 시 결과 : 20 */ [prompt] calc * 7 8 1 1 /*이와 같이 실행 file의 수행 시 결과 : 56 */ Chapter 13 Input/Output and Files 24

Double-Spacing a File [Ex] #include <stdio. h> #include <stdlib. h> void double_space( FILE *,

Double-Spacing a File [Ex] #include <stdio. h> #include <stdlib. h> void double_space( FILE *, FILE * ); void prn_info( char * ); prn_info()함수에서 exit()함수를 사용하기 때문에 포함시킴 명령어 라인의 인자로 두 개의 파일에 접근하게 되어있다. ex) a. out file 1 file 2 int main ( int argc, char **argv ) { ifp, ofp는 파일 포인터 FILE *ifp, *ofp; if( argc != 3 ) { exit()함수는 오류가 발생하면 prn_info(argv[0]); 0이 아닌 값을 리턴한다. exit(1); } ifp = fopen( argv[1], “r” ); /* open for reading */ ofp = fopen( argv[2], “w” ); /* open for writing */ fclose(ifp); fclose (ofp); return 0; } Chapter 13 Input/Output and Files 25

Double-Spacing a File void double_space( FILE *ifp, FILE *ofp ) { int c; while

Double-Spacing a File void double_space( FILE *ifp, FILE *ofp ) { int c; while ( ( c = getc(ifp) ) != EOF ) { putc(c, ofp); if ( c == ‘n’ ) putc(‘n’ ofp ); /* found newline – duplicate it */ } } void prn_info( char *pgm_name ) { printf(“n%s%s%snn”, “Usage: “, pgm_name, “infile outfile”, “The contents of infile will be double-spaced “, “and written to outfile. ” ); 실행파일이 dbl_sapce라면, } dbl_space file 1 file 2 로 실행한다. Chapter 13 Input/Output and Files 26

The I/O Function in stdio. h §. printf(“%d”, a); – standard I/O로 출력은 모니터

The I/O Function in stdio. h §. printf(“%d”, a); – standard I/O로 출력은 모니터 §. int fprintf(FILE fp, const char *control_string, …); – fp가 지정하는 파일에 문자를 쓰고 씌어진 문자의 개수를 리 턴 한다. §. int sprintf(char *s, const char *control_string, …); – 출력 결과를 화면에 출력하는 대신 s가 포인트하는 문자열에 쓴다. Chapter 13 Input/Output and Files 27

String I/O Function sprintf() § sprintf() – 문자열 (string) 처리를 위한 printf()문이다. – 결과를

String I/O Function sprintf() § sprintf() – 문자열 (string) 처리를 위한 printf()문이다. – 결과를 화면에 출력하는 대신에, 첫 번째 argument인 char형 포인터가 포인트하는 곳에 출력한다. § stdio. h 파일에 있는 sprintf()의 prototype int sprintf( char *s, const char *format, … ); § sprintf() Syntax sprintf( string, control_string, other_arguments ); Chapter 13 Input/Output and Files 29

String I/O Function sscanf() § sscanf() – 문자열 (String) 처리를 위한 scanf()문이다. – keyboard로

String I/O Function sscanf() § sscanf() – 문자열 (String) 처리를 위한 scanf()문이다. – keyboard로 입력을 받지 않고, 첫 번째 argument가 포인트하 는 곳으로부터 입력 받는다. § stdio. h 파일에 있는 sscanf()의 prototype int sscanf( const char *s, const char *format, … ); § sscanf() Syntax sscanf( string, control_string, other_arguments ); Chapter 13 Input/Output and Files 30

String I/O Function sprintf() and sscanf() [Ex] char in_string[] = “ 1 2 3

String I/O Function sprintf() and sscanf() [Ex] char in_string[] = “ 1 2 3 go”; char out_string[100], tmp[100]; int a, b, c; sscanf( in_string, “%d%d%d%s”, &a, &b, &c, tmp ); sprintf(out_string, “%s %s %d%d%dn”, tmp, a, b, c); printf(“%d”, out_string); go go 123 Chapter 13 Input/Output and Files 31

String I/O Function sprintf() and sscanf() § FILE I/O 를 포함한 예제 [Ex] #include

String I/O Function sprintf() and sscanf() § FILE I/O 를 포함한 예제 [Ex] #include <stdio. h> main() { char c, s[] = “abc”, *p = s; int i; FILE *ofp 1, *ofp 2; ofp 1 = fopen(“tmp 1. txt”, ”w”); ofp 2 = fopen(“tmp 2. txt”, ”w”); for( i = 0 ; i < 3 ; ++i ) { sscanf(s, “%c”, &c); fprintf( ofp 1, “%c”, c ); } ofp 1이 point하고 있는 파일에 문자를 write Chapter 13 Input/Output and Files for( i = 0 ; i < 3 ; ++i ) { sscanf(s, “%c”, &c); fprintf( ofp 2, “%c”, c ); } fclose(ofp 1); fclose(ofp 2); ofp 2가 point하고 있는 파일에 문자를 write } tmp 1. txt = abc tmp 2. txt = c₩ 337₩ 276 32

Line I/O Function fputs() [Ex] FILE *fp; char filen[] = "test"; int i; char

Line I/O Function fputs() [Ex] FILE *fp; char filen[] = "test"; int i; char *data[]={"to ben", "or notn", "to ben"}; fp = fopen(filen, "w"); for(i = 0; i<3; i++) 각 string끝에 ‘n’이 없는 경우 fputs( strcar( data[i], "n”), fp); fputs(data[i], fp); fclose(); Chapter 13 Input/Output and Files 34

Line I/O Function fgets() § gets함수와 fgets함수의 차이 – gets함수 : new line의 저장

Line I/O Function fgets() § gets함수와 fgets함수의 차이 – gets함수 : new line의 저장 안됨 ( new line은 자동 ''으로 convert됨 ) – fgets함수 : new line 의 read시 저장 됨 ( 끝에 ''자동 추가 ) [Ex] fgets(str, num, stdin); Chapter 13 Input/Output and Files KB통해 string의 read 36

Line I/O Function fputs() [Ex] /* file ‘testin’ -> file ‘test. out’ 으로 copy

Line I/O Function fputs() [Ex] /* file ‘testin’ -> file ‘test. out’ 으로 copy */ FILE *ip, *op; char line[80], c; ip = fopen("testin", "r"); op = fopen("testout", "w"); while( fgets(line, 80, ip) != NULL) fputs(line, op); fclose(ip); fclose(op); Chapter 13 Input/Output and Files ip가 지정하는 파일에서 80개까지의 문자를 읽어 line에 저장한다. 37

Using Temporary Files and Graceful Functions § tmpfile() – C에서 파일이 닫히거나 프로그램이 종료될

Using Temporary Files and Graceful Functions § tmpfile() – C에서 파일이 닫히거나 프로그램이 종료될 때 자동적으로 삭 제되는 임시 파일을 생성하기 위한 함수 – 최신의 자료로 수정되기 위해 “wb+” 모드로 열림 § tmpfile Syntax FILE *tmpfile(void); char *tmpnam(char *s); [Ex] FILE *tempptr; tempptr = tmpfile( ); /* creates a temporary file */ Chapter 13 Input/Output and Files 38

Using Temporary Files and Graceful Functions [Ex] /* 외부 파일의 내용을 소문자에서 대문자로 바꾸어

Using Temporary Files and Graceful Functions [Ex] /* 외부 파일의 내용을 소문자에서 대문자로 바꾸어 주는 프로그램 */ #include <stdio. h> #include <stdlib. h> #include <ctype. h> FILE *gfopen( char *filename, char *mode ); *gfopen함수의 prototype int main(int argc, char **argv) { int c; FILE *fp, *tmp_fp; 명령어 라인의 argument가 2개가 아니면 에러 메세지를 출력한다. if (argc != 2 ) { fprintf(stderr, “n%s%s%snn”, “Usage: “, argv[0], “ filename”, “The file will be doubled and som letters capitalized. “); exit(1); } /* continue… */ Chapter 13 Input/Output and Files 39

Using Temporary Files and Graceful Functions fp = gfopen(argv[1], “r+”); tmp_fp = tmpfile(); while

Using Temporary Files and Graceful Functions fp = gfopen(argv[1], “r+”); tmp_fp = tmpfile(); while ( ( c = getc(fp) ) != EOF ) putc(toupper(c) , tmp_fp ); fprintf(fp, “---n”); rewind(tmp_fp); while ( ( c = getc(tmp_fp) ) != EOF putc( c, fp ); return 0; 외부 파일을 r+ mode를 써서 open한다. 외부 파일의 내용을 character 단위로 입력받아 EOF가 될 때까지 toupper() 함수를 사용하여 대문자로 변환한다 ) file pointer의 indicator를 file의 시작하는 부분으로 옮긴다. tmp_fp에 저장되어있던 문자들을 출력하는 부분 } FILE *gfopen(char *fn, char *mode) 외부 파일 이름과 open mode 를 { argument로 입력받아 function 실행 FILE *fp; if( ( fp = fopen(fn, mode ) ) == NULL ) { fprintf(stderr, “Cannot open %s – bye!n”, fn ); exit(1); } C Programming return fp; } -----------Chapter 13 Input/Output and Files C PROGRAMMING 40

Accessing a File Randomly [Ex] #include <stdio. h> #define MAXSTRING 100 file_name이 가리키는 파일

Accessing a File Randomly [Ex] #include <stdio. h> #define MAXSTRING 100 file_name이 가리키는 파일 안에 C Programming 이라는 문장이 있다고 가정하여 설명. int main(void) { char file_name[MAXSTRING]; int c; FILE *ifp; fprintf(stderr, “n. Input a file name: “); 문장의맨 끝에서 0번째 위치에 scanf(“%s”, file_name ); ifp를 둔다. ( 13번째 위치 ) ifp = fopen(file_name, “r” ); fseek(ifp, 0, 2); 문장의 현재위치(위의 결과로 끝 문자) 에서 -1번째, 즉 앞 문자에 ifp를 둔다. fseek(ifp, -1, 1); /* continue */ ( 12번째 위치 ) Chapter 13 Input/Output and Files 42

Accessing a File Randomly while ( ftell(ifp) > 0) { c = getc(ifp); putchar(c);

Accessing a File Randomly while ( ftell(ifp) > 0) { c = getc(ifp); putchar(c); fseek(ifp, -2, 1); } return 0; } ifp가 0보다 클 동안 while 함수를 실행하는데 true일 경우 ifp의 indicator 값을 하나 증가시킨다. ( 13번째 위치 ) ifp가 point 하고 있는 문자를 출력 fseek함수를 이용하여 현재위치에서 앞에 두 번째 문자를 ifp로 한다. ( 11번째 위치 ) gnimmargar. P^ Chapter 13 Input/Output and Files 43

수고하셨습니다 Input / Output and Files

수고하셨습니다 Input / Output and Files