CHAPTER 19
EXTERNAL FILES

[IMAGE: An Quarter-Size Version of The Joy of C Front Cover]
Our earlier programs have accessed files solely through their standard input and output. But that's a severe limitation---those programs can access only one input and one output file. Fortunately, C provides a well-stocked library of functions for manipulating external files. This chapter presents most of these functions and uses them to write useful file-handling utilities. We also write a small package that allows us to use ``virtual arrays,'' data structures that behave like arrays but are actually stored in files rather than memory. The chapter concludes with an electronic address book that stores the addresses and phone numbers in an indexed external file.

Jump to: [Previous Chapter | Next Chapter]


  1. ACCESSING EXTERNAL FILES
  2. THE STANDARD FILES
  3. RANDOM FILE ACCESS
  4. BLOCK INPUT AND OUTPUT
  5. FILE UPDATING
  6. CASE STUDY: AN ELECTRONIC ADDRESS BOOK

Objectives


File을 사용한 입출력은 file pointer를 사용한다.



File을 사용하기 전에 fopen function을 사용하여 file을 open하여야 한다.

file pointer variable = fopen(file name, mode);
file name : string
mode : "r", "w", 또는 "a" (read, write, 또는 append)



사용이 끝난 file은 fclose function을 사용하여 닫는다.



File I/O functions

Function기능
int getc(FILE *fp)character 입력
int putc(int c, FILE *fp)character 출력
char *fgets(char *line, int MaxLine, FILE *fp) 한 줄의 string 입력
int fputs(char *line, FILE *fp)한 줄의 string 출력
int fscanf(FILE *fp, char *format, arg1, arg2, ...) 양식을 갖는 입력
int fprintf(FILE *fp, char *format, arg1, arg2, ...) 양식을 갖는 출력
int ungetc(int c, FILE *fp)입력한 문자를 다시 file로 원위치


세 개의 standard I/O file이 다음 목적으로 "stdio.h"에 정의되어 있다.



Standard I/O functions



String에서의 입출력



scanf function 사용

scanf function을 이용해 data를 입력하기 위해서는 입력할 data를 저장할 메모리 주소를 argument로 주어야 한다.
scanf function의 format은 printf function의 format과 유사하며 다음과 같이 처리된다.



사용 예) 원소명(element name), 화학기호(chemical symbol), 원자번호(atomic number), 원자가(atomic weight)가 다음 형식으로 된 자료 입력 (elements.c, elements.dat)



Standard I/O redirection과 pipe (MS-DOS와 UNIX OS에서 유용)

Standard I/O로부터의 입출력을 file 또는 앞 프로세스의 출력으로 전환




실습 1) 한 file을 다른 file로 복사하는 프로그램을 작성하라. (filecopy.c, filecpy1.c, filecpy2.c)

실행 예: "srcfile"을 "dstfile"로 복사
filecopy srcfile dstfile

실습 2) File을 읽어 그 file에 포함된 단어를 한 줄에 하나씩 프린트하고 마지막에 줄, 단어, 문자 수를 프린트하는 프로그램을 작성하라. 각 단어는 white-space로 구분된다. (입력 file은 임의의 C program source file로 하고 file open version과 input redirection version 두 방법을 시도해 볼 것)



[ Table Of Contents]