PointerStreamDefault_第1頁(yè)
PointerStreamDefault_第2頁(yè)
PointerStreamDefault_第3頁(yè)
PointerStreamDefault_第4頁(yè)
PointerStreamDefault_第5頁(yè)
已閱讀5頁(yè),還剩155頁(yè)未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

1、Copyright 2008 W. W. Norton & Company.All rights reserved.1Chapter 22Input/OutputIntroductionCs input/output library is the biggest and most important part of the standard library.The header is the primary repository of input/output functions, including printf, scanf, putchar, getchar, puts, and get

2、s.This chapter provides more information about these six functions.It also introduces many new functions, most of which deal with files.Copyright 2008 W. W. Norton & Company.All rights reserved.2IntroductionTopics to be covered:Streams, the FILE type, input and output redirection, and the difference

3、 between text files and binary filesFunctions designed specifically for use with files, including functions that open and close filesFunctions that perform “formatted” input/outputFunctions that read and write unformatted data (characters, lines, and blocks)Random access operations on filesFunctions

4、 that write to a string or read from a stringCopyright 2008 W. W. Norton & Company.All rights reserved.3IntroductionIn C99, some I/O functions belong to the header.The functions deal with wide characters rather than ordinary characters.Functions in that read or write data are known as byte input/out

5、put functions. Similar functions in are called wide-character input/output functions.Copyright 2008 W. W. Norton & Company.All rights reserved.4StreamsIn C, the term stream means any source of input or any destination for output.Many small programs obtain all their input from one stream (the keyboar

6、d) and write all their output to another stream (the screen).Larger programs may need additional streams.Streams often represent files stored on various media.However, they could just as easily be associated with devices such as network ports and printers.Copyright 2008 W. W. Norton & Company.All ri

7、ghts reserved.5File PointersAccessing a stream is done through a file pointer, which has type FILE *.The FILE type is declared in .Certain streams are represented by file pointers with standard names.Additional file pointers can be declared as needed:FILE *fp1, *fp2;Copyright 2008 W. W. Norton & Com

8、pany.All rights reserved.6Standard Streams and Redirection provides three standard streams:File PointerStreamDefault MeaningstdinStandard inputKeyboardstdoutStandard outputScreenstderrStandard errorScreen These streams are ready to usewe dont declare them, and we dont open or close them.Copyright 20

9、08 W. W. Norton & Company.All rights reserved.7Standard Streams and RedirectionThe I/O functions discussed in previous chapters obtain input from stdin and send output to stdout.Many operating systems allow these default meanings to be changed via a mechanism known as redirection.Copyright 2008 W. W

10、. Norton & Company.All rights reserved.8Standard Streams and RedirectionA typical technique for forcing a program to obtain its input from a file instead of from the keyboard:demo out.datAll data written to stdout will now go into the out.dat file instead of appearing on the screen.Copyright 2008 W.

11、 W. Norton & Company.All rights reserved.9Standard Streams and RedirectionInput redirection and output redirection can be combined:demo out.datThe characters dont have to be adjacent to file names, and the order in which the redirected files are listed doesnt matter:demo out.datdemo out.dat in.datCo

12、pyright 2008 W. W. Norton & Company.All rights reserved.10Standard Streams and RedirectionOne problem with output redirection is that everything written to stdout is put into a file.Writing error messages to stderr instead of stdout guarantees that they will appear on the screen even when stdout has

13、 been redirected.Copyright 2008 W. W. Norton & Company.All rights reserved.11Text Files versus Binary Files supports two kinds of files: text and binary.The bytes in a text file represent characters, allowing humans to examine or edit the file.The source code for a C program is stored in a text file

14、.In a binary file, bytes dont necessarily represent characters.Groups of bytes might represent other types of data, such as integers and floating-point numbers.An executable C program is stored in a binary file.Copyright 2008 W. W. Norton & Company.All rights reserved.12Text Files versus Binary File

15、sText files have two characteristics that binary files dont possess.Text files are divided into lines. Each line in a text file normally ends with one or two special characters.Windows: carriage-return character (x0d) followed by line-feed character (x0a)UNIX and newer versions of Mac OS: line-feed

16、characterOlder versions of Mac OS: carriage-return characterCopyright 2008 W. W. Norton & Company.All rights reserved.13Text Files versus Binary FilesText files may contain a special “end-of-file” marker.In Windows, the marker is x1a (Ctrl-Z), but it is not required.Most other operating systems, inc

17、luding UNIX, have no special end-of-file character.In a binary file, there are no end-of-line or end-of-file markers; all bytes are treated equally.Copyright 2008 W. W. Norton & Company.All rights reserved.14Text Files versus Binary FilesWhen data is written to a file, it can be stored in text form

18、or in binary form.One way to store the number 32767 in a file would be to write it in text form as the characters 3, 2, 7, 6, and 7:Copyright 2008 W. W. Norton & Company.All rights reserved.15Text Files versus Binary FilesThe other option is to store the number in binary, which would take as few as

19、two bytes:Storing numbers in binary can often save space.Copyright 2008 W. W. Norton & Company.All rights reserved.16Text Files versus Binary FilesPrograms that read from a file or write to a file must take into account whether its text or binary.A program that displays the contents of a file on the

20、 screen will probably assume its a text file.A file-copying program, on the other hand, cant assume that the file to be copied is a text file.If it does, binary files containing an end-of-file character wont be copied completely.When we cant say for sure whether a file is text or binary, its safer t

21、o assume that its binary.Copyright 2008 W. W. Norton & Company.All rights reserved.17File OperationsSimplicity is one of the attractions of input and output redirection.Unfortunately, redirection is too limited for many applications.When a program relies on redirection, it has no control over its fi

22、les; it doesnt even know their names.Redirection doesnt help if the program needs to read from two files or write to two files at the same time.When redirection isnt enough, well use the file operations that provides.Copyright 2008 W. W. Norton & Company.All rights reserved.18Opening a FileOpening a

23、 file for use as a stream requires a call of the fopen function.Prototype for fopen:FILE *fopen(const char * restrict filename, const char * restrict mode);filename is the name of the file to be opened.This argument may include information about the files location, such as a drive specifier or path.

24、mode is a “mode string” that specifies what operations we intend to perform on the file.Copyright 2008 W. W. Norton & Company.All rights reserved.19Opening a FileThe word restrict appears twice in the prototype for fopen.restrict, which is a C99 keyword, indicates that filename and mode should point

25、 to strings that dont share memory locations.The C89 prototype for fopen doesnt contain restrict but is otherwise identical.restrict has no effect on the behavior of fopen, so it can usually be ignored.Copyright 2008 W. W. Norton & Company.All rights reserved.20Opening a FileIn Windows, be careful w

26、hen the file name in a call of fopen includes the character.The callfopen(c:projecttest1.dat, r)will fail, because t is treated as a character escape.One way to avoid the problem is to use instead of :fopen(c:projecttest1.dat, r)An alternative is to use the / character instead of :fopen(c:/project/t

27、est1.dat, r)Copyright 2008 W. W. Norton & Company.All rights reserved.21Opening a Filefopen returns a file pointer that the program can (and usually will) save in a variable:fp = fopen(in.dat, r); /* opens in.dat for reading */When it cant open a file, fopen returns a null pointer.Copyright 2008 W.

28、W. Norton & Company.All rights reserved.22ModesFactors that determine which mode string to pass to fopen:Which operations are to be performed on the fileWhether the file contains text or binary dataCopyright 2008 W. W. Norton & Company.All rights reserved.23ModesMode strings for text files:String Me

29、aningrOpen for readingwOpen for writing (file need not exist)aOpen for appending (file need not exist)r+Open for reading and writing, starting at beginningw+Open for reading and writing (truncate if file exists)a+Open for reading and writing (append if file exists)Copyright 2008 W. W. Norton & Compa

30、ny.All rights reserved.24ModesMode strings for binary files:String MeaningrbOpen for readingwbOpen for writing (file need not exist)abOpen for appending (file need not exist)r+b or rb+Open for reading and writing, starting at beginningw+b or wb+Open for reading and writing (truncate if file exists)a

31、+b or ab+Open for reading and writing (append if file exists)Copyright 2008 W. W. Norton & Company.All rights reserved.25ModesNote that there are different mode strings for writing data and appending data.When data is written to a file, it normally overwrites what was previously there.When a file is

32、 opened for appending, data written to the file is added at the end.Copyright 2008 W. W. Norton & Company.All rights reserved.26ModesSpecial rules apply when a file is opened for both reading and writing.Cant switch from reading to writing without first calling a file-positioning function unless the

33、 reading operation encountered the end of the file.Cant switch from writing to reading without either calling fflush or calling a file-positioning function.Copyright 2008 W. W. Norton & Company.All rights reserved.27Closing a FileThe fclose function allows a program to close a file that its no longe

34、r using.The argument to fclose must be a file pointer obtained from a call of fopen or freopen.fclose returns zero if the file was closed successfully.Otherwise, it returns the error code EOF (a macro defined in ).Copyright 2008 W. W. Norton & Company.All rights reserved.28Closing a FileThe outline

35、of a program that opens a file for reading:#include #include #define FILE_NAME example.datint main(void) FILE *fp; fp = fopen(FILE_NAME, r); if (fp = NULL) printf(Cant open %sn, FILE_NAME); exit(EXIT_FAILURE); fclose(fp); return 0;Copyright 2008 W. W. Norton & Company.All rights reserved.29Closing a

36、 FileIts not unusual to see the call of fopen combined with the declaration of fp:FILE *fp = fopen(FILE_NAME, r);or the test against NULL:if (fp = fopen(FILE_NAME, r) = NULL) Copyright 2008 W. W. Norton & Company.All rights reserved.30Attaching a File to an Open Streamfreopen attaches a different fi

37、le to a stream thats already open.The most common use of freopen is to associate a file with one of the standard streams (stdin, stdout, or stderr).A call of freopen that causes a program to begin writing to the file foo:if (freopen(foo, w, stdout) = NULL) /* error; foo cant be opened */Copyright 20

38、08 W. W. Norton & Company.All rights reserved.31Attaching a File to an Open Streamfreopens normal return value is its third argument (a file pointer).If it cant open the new file, freopen returns a null pointer.Copyright 2008 W. W. Norton & Company.All rights reserved.32Attaching a File to an Open S

39、treamC99 adds a new twist: if filename is a null pointer, freopen attempts to change the streams mode to that specified by the mode parameter.Implementations arent required to support this feature.If they do, they may place restrictions on which mode changes are permitted.Copyright 2008 W. W. Norton

40、 & Company.All rights reserved.33Obtaining File Names from the Command LineThere are several ways to supply file names to a program.Building file names into the program doesnt provide much flexibility.Prompting the user to enter file names can be awkward.Having the program obtain file names from the

41、 command line is often the best solution.An example that uses the command line to supply two file names to a program named demo:demo names.dat dates.datCopyright 2008 W. W. Norton & Company.All rights reserved.34Obtaining File Names from the Command LineChapter 13 showed how to access command-line a

42、rguments by defining main as a function with two parameters:int main(int argc, char *argv) argc is the number of command-line arguments.argv is an array of pointers to the argument strings.Copyright 2008 W. W. Norton & Company.All rights reserved.35Obtaining File Names from the Command Lineargv0 poi

43、nts to the program name, argv1 through argvargc-1 point to the remaining arguments, and argvargc is a null pointer.In the demo example, argc is 3 and argv has the following appearance:Copyright 2008 W. W. Norton & Company.All rights reserved.36Program: Checking Whethera File Can Be OpenedThe canopen

44、.c program determines if a file exists and can be opened for reading.The user will give the program a file name to check:canopen fileThe program will then print either file can be opened or file cant be opened.If the user enters the wrong number of arguments on the command line, the program will pri

45、nt the message usage: canopen filename.Copyright 2008 W. W. Norton & Company.All rights reserved.37canopen.c/* Checks whether a file can be opened for reading */#include #include int main(int argc, char *argv) FILE *fp; if (argc != 2) printf(usage: canopen filenamen); exit(EXIT_FAILURE); if (fp = fo

46、pen(argv1, r) = NULL) printf(%s cant be openedn, argv1); exit(EXIT_FAILURE); printf(%s can be openedn, argv1); fclose(fp); return 0;Copyright 2008 W. W. Norton & Company.All rights reserved.38Temporary FilesPrograms often need to create temporary filesfiles that exist only as long as the program is

47、running. provides two functions, tmpfile and tmpnam, for working with temporary files.Copyright 2008 W. W. Norton & Company.All rights reserved.39Temporary Filestmpfile creates a temporary file (opened in wb+ mode) that will exist until its closed or the program ends.A call of tmpfile returns a file

48、 pointer that can be used to access the file later:FILE *tempptr;tempptr = tmpfile(); /* creates a temporary file */If it fails to create a file, tmpfile returns a null pointer.Copyright 2008 W. W. Norton & Company.All rights reserved.40Temporary FilesDrawbacks of using tmpfile:Dont know the name of

49、 the file that tmpfile creates.Cant decide later to make the file permanent.The alternative is to create a temporary file using fopen.The tmpnam function is useful for ensuring that this file doesnt have the same name as an existing file.Copyright 2008 W. W. Norton & Company.All rights reserved.41Te

50、mporary Filestmpnam generates a name for a temporary file.If its argument is a null pointer, tmpnam stores the file name in a static variable and returns a pointer to it:char *filename;filename = tmpnam(NULL); /* creates a temporary file name */Copyright 2008 W. W. Norton & Company.All rights reserv

51、ed.42Temporary FilesOtherwise, tmpnam copies the file name into a character array provided by the programmer:char filenameL_tmpnam;tmpnam(filename); /* creates a temporary file name */In this case, tmpnam also returns a pointer to the first character of this array.L_tmpnam is a macro in that specifi

52、es how long to make a character array that will hold a temporary file name.Copyright 2008 W. W. Norton & Company.All rights reserved.43Temporary FilesThe TMP_MAX macro (defined in ) specifies the maximum number of temporary file names that can be generated by tmpnam.If it fails to generate a file na

53、me, tmpnam returns a null pointer.Copyright 2008 W. W. Norton & Company.All rights reserved.44File BufferingTransferring data to or from a disk drive is a relatively slow operation.The secret to achieving acceptable performance is buffering.Data written to a stream is actually stored in a buffer are

54、a in memory; when its full (or the stream is closed), the buffer is “flushed.”Input streams can be buffered in a similar way: the buffer contains data from the input device; input is read from this buffer instead of the device itself.Copyright 2008 W. W. Norton & Company.All rights reserved.45File B

55、ufferingBuffering can result in enormous gains in efficiency, since reading a byte from a buffer or storing a byte in a buffer is very fast.It takes time to transfer the buffer contents to or from disk, but one large “block move” is much faster than many tiny byte moves.The functions in perform buff

56、ering automatically when it seems advantageous.On rare occasions, we may need to use the functions fflush, setbuf, and setvbuf.Copyright 2008 W. W. Norton & Company.All rights reserved.46File BufferingBy calling fflush, a program can flush a files buffer as often as it wishes.A call that flushes the

57、 buffer for the file associated with fp:fflush(fp); /* flushes buffer for fp */A call that flushes all output streams:fflush(NULL); /* flushes all buffers */fflush returns zero if its successful and EOF if an error occurs.Copyright 2008 W. W. Norton & Company.All rights reserved.47File Bufferingsetv

58、buf allows us to change the way a stream is buffered and to control the size and location of the buffer.The functions third argument specifies the kind of buffering desired:_IOFBF (full buffering)_IOLBF (line buffering)_IONBF (no buffering)Full buffering is the default for streams that arent connect

59、ed to interactive devices.Copyright 2008 W. W. Norton & Company.All rights reserved.48File Bufferingsetvbufs second argument (if its not a null pointer) is the address of the desired buffer.The buffer might have static storage duration, automatic storage duration, or even be allocated dynamically.se

60、tvbufs last argument is the number of bytes in the buffer.Copyright 2008 W. W. Norton & Company.All rights reserved.49File BufferingA call of setvbuf that changes the buffering of stream to full buffering, using the N bytes in the buffer array as the buffer:char bufferN;setvbuf(stream, buffer, _IOFB

溫馨提示

  • 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論