版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
1、Programming in CLecture 8: C File ProcessingOutlinenData and Data FilesnFiles and StreamsnSequential Access FilesnRandom Access Files2Data and Data FilesnData Files can be created, updated, and processed by C programs nused for permanent storage(持久存儲) of large amounts of datanStorage of data in vari
2、ables and arrays is only temporary(臨時(shí)的)nAll such data are lost when the program terminates3The Data Hierarchy - 1nBit smallest data itemnValue of 0 or 1nByte 8 bits nUsed to store a character: Decimal digits, letters, and special symbolsnField group of characters conveying meaning nExample: your nam
3、e4The Data Hierarchy - 2nRecord group of related fieldsnRepresented by a struct (or a class in C+)nExample: In a payroll system, a record for a particular employee that contained his/her identification number (possible record key), name, address, etc.nFile group of related recordsnExample: payroll f
4、ilenDatabase group of related files5The Data Hierarchy - 36The Data Hierarchy - 4nExample (Fig. 11.1):1Bit01001010ByteJudyFieldJudyGreenRecordSallyBlackJudyBlueIrisOrangeRandyRedFile7OutlinenData and Data FilesnFiles and StreamsnSequential Access FilesnRandom Access Files8Files and StreamsnC views e
5、ach file as a sequence of bytesnFile ends with the end-of-file (EOF) markernOr, file ends at a specified byte9EOF and feof() are defined in .Example: while (c = getchar() != EOF) if (!feof(stdin) EOF Key CombinationsnDifferent for different OS:10Computer systemKey combinationUNIX systems dWindows zM
6、acintosh dVAX(VMS) zFiles and StreamsnA Stream is created when a file is openednProvide communication channel(通信渠道) between files and programsnOpening a file returns a pointer to a FILE structurenExample file pointers:nstdin - standard input (keyboard)nstdout - standard output (screen)nstderr - stan
7、dard error (screen)11FILE structuren*The programmer need not know the specifics of the FILE structure to use files.nFile descriptor(文件描述符)nIndex into operating system (OS) array called the open file tablenFile Control Block (FCB)nFound in every array element, system uses it to administer the file(Re
8、fer to Fig. 11.5 on page 437)12OutlinenData and Data FilesnFiles and StreamsnSequential Access FilesnRandom Access Files13Read/Write Functions - 1#include nint fgetc(FILE *stream)nRead one character from a filenTake a FILE pointer as an argumentnfgetc(stdin) equivalent to getchar()nint fputc(int c,
9、FILE *stream)nWrite one character to a filenTake a FILE pointer and a character to be written as argumentsnfputc(a, stdout) equivalent to putchar(a)14Read/Write functions - 2nchar* fgets(char *s, int n, FILE *stream)nReads a line from a filenint fputs(char *s, FILE *stream)nWrites a line to a filenf
10、scanf / fprintfnint fscanf(FILE *stream, const char * format, )nint fprintf(FILE *stream, const char * format, )nFile processing equivalents of scanf and printf1516 /* Framework for Create a sequential file, see Fig. 11.3 on P433 for details */ #include int main() FILE *cfPtr; /* cfPtr = clients.dat
11、 file pointer */if ( ( cfPtr = fopen( clients.dat, w ) ) = NULL )printf( File could not be opened.n );else scanf( %d%s%lf, &account, name, &balance ); while ( !feof( stdin ) ) fprintf( cfPtr, %d %s %.2fn, account, name, balance );printf( ? );scanf( %d%s%lf, &account, name, &balance )
12、;fclose( cfPtr );return 0; Creating a Sequential Access FilenFILE *cfPtr;nDeclares a FILE pointer called cfPtrncfPtr = fopen(clients.dat, w);nFunction fopen returns a FILE pointer to file specifiednTakes two arguments the file to be opened and the open modenIf open fails, NULL is returned17Creating
13、a Sequential Access FilenfprintfnUsed to print to a filenLike printf, except first argument is a FILE pointer (pointer to the file you want to print )nfeof(FILE pointer)nReturns true if end-of-file (EOF) indicator (no more data to process) is set for the specified filenfclose(FILE pointer)nCloses sp
14、ecified filenPerformed automatically when program endsnGood practice: close files explicitly18File Open Modes19Computer systemKey combinationrOpen a file for reading. wCreate a file for writing. If the file already exists, discard the current contents. aAppend; open or create a file for writing at e
15、nd of file. r+Open a file for update (reading and writing); 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. rbOpen a file for reading i
16、n binary mode. wbCreate a file for writing in binary mode. If the file already exists, discard the current contents. abAppend; open or create a file for writing at end of file in binary mode. rb+ (or r+b)Open a file for update (reading and writing) in binary mode. wb+ (or w+b)Create a file for updat
17、e (reading and writing) in binary mode. If the file already exists, discard the current contents. ab+ (or a+b)Read and Append; open or create a file for update in binary mode; writing is done at the end of the file. Sequential Access FilesnAlso called text file (文本文件)nEach byte stores an ASCII code,
18、 representing a characternFormat of data in a text file is not identical with its format stored in memory.nE.g. 7,-14 are ints occupying 4 bytes each internally;but they are of different size(1 and 3 bytes) as text in a file.2021/* Fig. 11.7: reading and printing a sequential file*/#include int main
19、() FILE *cfPtr; /* cfPtr = clients.dat file pointer */if ( ( cfPtr = fopen( clients.dat, r ) ) = NULL )printf( File could not be openedn );else printf( %-10s%-13s%sn, Account, Name, Balance );fscanf( cfPtr, %d%s%lf, &account, name, &balance );while ( !feof( cfPtr ) ) printf( %-10d%-13s%7.2fn
20、, account, name, balance );fscanf( cfPtr, %d%s%lf, &account, name, &balance ); fclose( cfPtr ); return 0;Reading Data from a Sequential Access FilenCreate a FILE pointer, link it to the file to readncfPtr = fopen( “clients.dat, r );nUse fscanf to read from the filenLike scanf, except first a
21、rgument is a FILE pointernfscanf( cfPtr, %d%s%f, &accounnt, name, &balance );nData read from beginning to end22Reading Data from a Sequential Access FilenFile position pointernIndicates number of next byte to be read / writtennNot really a pointer, but an integer value (specifies byte locati
22、on)nAlso called byte offsetnrewind( cfPtr )nRepositions file position pointer to beginning of file (byte 0)23Reading Data from a Sequential Access FilenFields can vary in sizenDifferent representation in files and screen than internal representationn1, 34, -890 are all ints, but have different sizes
23、 in filenCannot be modified without the risk of destroying other data(修改文件內(nèi)容時(shí)有可能破壞不該破壞的數(shù)據(jù))24Reading Data from a Sequential Access File25300 White 0.00 400 Jones 32.87 (old data in file)If we want to change “White” to “Worthington”,300 White 0.00 400 Jones 32.87300 Worthington 0.00ones 32.87300 Worth
24、ington 0.00Data gets overwrittenOutlinenData and Data FilesnFiles and StreamsnSequential Access FilesnRandom Access Files26Random Access FilesnAlso called binary files(二進(jìn)制文件)nFormat of data in a binary file is identical(同樣的) with its format stored in memory.nbyte doesnt necessarily represent charact
25、er; groups of bytes might represent other types of data, such as integers and floating-point numbersnRecords in binary files have identical length.27Random Access FilesnExample:28001100010011001000110011001101000011010100000000000000000011000000111001123451 2 3 4 5ASCII codes of 5 charactersAn integ
26、erRandom Access FilesnAccess individual records without searching through other recordsnInstant access to records in a file(對文件記錄的隨機(jī)訪問)nData can be inserted without destroying other datanData previously stored can be updated or deleted without overwriting29Random Access FilesnC view of a random-acce
27、ss file:30100Bytes100Bytes100Bytes100Bytes100Bytes100Bytes0100200300400500ByteOffsets31/* Fig. 11.11: Creating a randomly accessed file sequentially , with empty structs. */#include struct clientData int acctNum; char lastName 15 ; char firstName 10 ; double balance;int main() int i;struct clientDat
28、a blankClient = 0, , , 0.0 ;FILE *cfPtr; if ( ( cfPtr = fopen( credit.dat, w ) ) = NULL )printf( File could not be opened.n );else for ( i = 1; i = 100; i+ )fwrite( &blankClient, sizeof( struct clientData ), 1, cfPtr );fclose( cfPtr );return 0;Unformatted File I/O Functionsnfwrite - Transfer byt
29、es from a location in memory to a filensize_t fwrite(const void * buffer, size_t size, size_t nmemb, FILE * fp);nfread - Transfer bytes from a file to a location in memorynsize_t fread(void * buffer, size_t size, size_t nmemb, FILE * fp);32Unformatted File I/O FunctionsnExample:nfwrite( &number,
30、 sizeof( int ), 1, myPtr ); nNumber - an integer variablen&number - location to transfer bytes fromnsizeof( int ) - number of bytes to transfern1 - for arrays, number of elements to transfernIn this case, one element of an array, i.e. one number is being transferrednmyPtr - File to transfer tonf
31、read similar 33Unformatted File I/O Functionsnfwrite( &myObject, sizeof (struct myStruct), 1, myPtr );nTo write a data block with designated size to a filensizeof return the size in bytes of the object in parenthesesnTo write several array elementsnPointer to array as first argumentnNumber of el
32、ements to write as third argument3435/* Fig. 11.12: Writing to a random access file*/.int main() FILE *cfPtr;struct clientData client = 0, , , 0.0 ;if ( ( cfPtr = fopen( credit.dat, r+ ) ) = NULL )printf( File could not be opened.n );else while ( client.acctNum != 0 ) printf( Enter lastname, firstna
33、me, balancen? );fscanf( stdin, %s%s%lf, client.lastName, client.firstName, &client.balance );fseek( cfPtr, ( client.acctNum - 1 ) * sizeof( struct clientData ), SEEK_SET );fwrite( &client, sizeof( struct clientData ), 1, cfPtr );printf( Enter account numbern? );scanf( %d, &client.acctNum
34、 );fclose( cfPtr ); return 0;Writing Data Randomly to a Random Access Filenint fseek( FILE *stream, long int offset, int whence);nSet the file position pointer to a specific positionnstream - pointer to filenoffset - file position pointer (0 is first location)nwhence - specifies where in file we are
35、 reading fromnSEEK_SET - seek starts at beginning of filenSEEK_CUR - seek starts at current location in filenSEEK_END - seek starts at end of filenSucceed: return 036Writing Data Randomly to a Random Access File37/*Fig. 11.15 Reading a random access file sequentially */ int main() FILE *cfPtr;struct
36、 clientData client;if ( ( cfPtr = fopen( credit.dat, r ) ) = NULL )printf( File could not be opened.n );else printf( %-6s%-16s%-11s%10sn, Acct, Last Name, First Name, Balance );while ( fread( &client, sizeof( struct clientData ), 1, cfPtr ) ) if ( client.acctNum != 0 )printf( %-6d%-16s%-11s%10.2fn, client.acctNum, client.lastName, client.firstName, client.balance );fclose( cfPtr ); return 0; Reading Data Sequentially from a Random Access Filenint fread(
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 服裝紡織行業(yè)的顧問工作總結(jié)
- 2025年全球及中國無人值守汽車衡亭行業(yè)頭部企業(yè)市場占有率及排名調(diào)研報(bào)告
- 2025年全球及中國化學(xué)鍍鎳 PTFE 涂層行業(yè)頭部企業(yè)市場占有率及排名調(diào)研報(bào)告
- 2025年全球及中國一體式旋轉(zhuǎn)變壓器行業(yè)頭部企業(yè)市場占有率及排名調(diào)研報(bào)告
- 2025-2030全球軟組織水平種植體行業(yè)調(diào)研及趨勢分析報(bào)告
- 2025-2030全球保險(xiǎn)業(yè)的低代碼和無代碼 (LCNC) 平臺行業(yè)調(diào)研及趨勢分析報(bào)告
- 2025年全球及中國加熱架式食物加熱器行業(yè)頭部企業(yè)市場占有率及排名調(diào)研報(bào)告
- 2025年全球及中國商用車氣制動防抱死制動系統(tǒng)行業(yè)頭部企業(yè)市場占有率及排名調(diào)研報(bào)告
- 2025年全球及中國熱水浴缸用換熱器行業(yè)頭部企業(yè)市場占有率及排名調(diào)研報(bào)告
- 2025年全球及中國變電站智能巡視解決方案行業(yè)頭部企業(yè)市場占有率及排名調(diào)研報(bào)告
- 運(yùn)動技能學(xué)習(xí)與控制完整
- 原料驗(yàn)收標(biāo)準(zhǔn)知識培訓(xùn)課件
- Unit4MyfamilyStorytime(課件)人教新起點(diǎn)英語三年級下冊
- 物流運(yùn)作管理-需求預(yù)測
- 財(cái)務(wù)管理專業(yè)《生產(chǎn)實(shí)習(xí)》教學(xué)大綱
- 一年級口算天天練(可直接打印)
- 新急救常用儀器設(shè)備操作流程
- 新人教版高中數(shù)學(xué)選擇性必修第一冊全套精品課件
- 2023年四川省自貢市中考數(shù)學(xué)真題(原卷版)
- 三年級數(shù)學(xué)混合運(yùn)算100題
- 通信工程安全生產(chǎn)手冊
評論
0/150
提交評論