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]