【正文】
int main() { …… FILE *cfPtr。 printf( ? )。 } Creating a Sequential Access File ? FILE *cfPtr。 the file must exists. w+ Create an empty file for both reading and writing. If the file already exists, discard the current contents. a+ Open a file for reading and appending。 writing is done at the end of the file. Sequential Access Files ? Also called text file (文本文件 ) ? Each byte stores an ASCII code, representing a character ? Format of data in a text file is not identical with its format stored in memory. ? . 7,14 are ints occupying 4 bytes each internally。 fscanf( cfPtr, %d%s%lf, account, name, balance )。 } return 0。 groups of bytes might represent other types of data, such as integers and floatingpoint numbers ? Records in binary files have identical length. 27 Random Access Files ? Example: 28 00110001 00110010 00110011 00110100 00110101 00000000 00000000 00110000 00111001 12345 1 2 3 4 5 ASCII codes of 5 characters An integer Random Access Files ? Access individual records without searching through other records ? Instant access to records in a file (對文件記錄的隨機訪問 ) ? Data can be inserted without destroying other data ? Data previously stored can be updated or deleted without overwriting 29 Random Access Files ? C’ view of a randomaccess file: 30 100 Bytes 100 Bytes 100 Bytes 100 Bytes 100 Bytes 100 Bytes 0 100 200 300 400 500 Byte Offsets 31 /* Fig. : Creating a randomly accessed file sequentially , with empty structs. */ include struct clientData { int acctNum。 }。 if ( ( cfPtr = fopen( , w ) ) == NULL ) printf( File could not be opened.\n )。 fclose( cfPtr )。 32 Unformatted File I/O Functions ? Example: ? fwrite( number, sizeof( int ), 1, myPtr )。 if ( ( cfPtr = fopen( , r+ ) ) == NULL ) printf( File could not be opened.\n )。 fwrite( client, sizeof( struct clientData ), 1, cfPtr )。 } return 0。 if ( ( cfPtr = fopen( , r ) ) == NULL ) printf( File could not be opened.\n )。 } return 0。 define PI 。 ? Reads a specified number of bytes from a file into memory ? Can read several fixedsize array elements ? Provide pointer to array ? Indicate number of elements to read ? Number specified in the 3rd argument ? return the number of items successfully read 38 Summary 本章重要內容: ? C語言中文件的分類 ? 順序文件 (文本文件 )的讀寫操作 ? 隨機文件 (二進制文件 )的讀寫操作 ? 兩類文件的異同 39 A few words on C Preprocessing 40 Introduction ? Handle by the preprocessor ? Not the C plier! ? Processed prior to pilation 編譯前進行 ? All headed with 井號開頭 Procedures to develop a C program 41