?? p3
字號:
.NHTHE STANDARD I/O LIBRARY.PPThe ``Standard I/O Library''is a collection of routinesintended to provideefficientand portableI/O servicesfor most C programs.The standard I/O library is available on each system that supports C,so programs that confinetheir system interactionsto its facilitiescan be transported from one system to another essentially without change..PPIn this section, we will discuss the basics of the standard I/O library.The appendix contains a more complete description of its capabilities..NH 2File Access.PPThe programs written so far have allread the standard input and written the standard output,which we have assumed are magically pre-defined.The next stepis to write a program that accessesa file that is.ulnotalready connected to the program.One simple example is.IT wc ,which counts the lines, words and charactersin a set of files.For instance, the command.P1wc x.c y.c.P2prints the number of lines, words and charactersin.UL x.cand.UL y.cand the totals..PPThe question is how to arrange for the named filesto be read \(emthat is, how to connect the file system names to the I/O statements which actually read the data..PPThe rules are simple.Before it can be read or writtena file has to be.ulopenedby the standard library function.UL fopen ..UL fopentakes an external name(like.UL x.cor.UL y.c ),does some housekeeping and negotiation with the operating system,and returns an internal namewhich must be used in subsequentreads or writes of the file..PPThis internal name is actually a pointer,called a.IT file.IT pointer ,to a structurewhich contains information about the file,such as the location of a buffer,the current character position in the buffer,whether the file is being read or written,and the like.Users don't need to know the details,because part of the standard I/O definitionsobtained by including.UL stdio.his a structure definition called.UL FILE .The only declaration needed for a file pointeris exemplified by.P1FILE *fp, *fopen();.P2This says that.UL fpis a pointer to a.UL FILE ,and.UL fopenreturns a pointer toa.UL FILE ..UL FILE \& (is a type name, like.UL int ,not a structure tag..PPThe actual call to.UL fopenin a programis.P1fp = fopen(name, mode);.P2The first argument of.UL fopenis thenameof the file,as a character string.The second argument is themode,also as a character string,which indicates how you intend touse the file.The only allowable modes areread.UL \&"r" ), (write.UL \&"w" ), (or append.UL \&"a" ). (.PPIf a file that you open for writing or appending does not exist,it is created(if possible).Opening an existing file for writing causes the old contentsto be discarded.Trying to read a file that does not existis an error,and there may be other causes of erroras well(like trying to read a filewhen you don't have permission).If there is any error,.UL fopenwill return the null pointervalue.UL NULL (which is defined as zero in.UL stdio.h )..PPThe next thing needed is a way to read or write the fileonce it is open.There are several possibilities,of which.UL getcand.UL putcare the simplest..UL getcreturns the next character from a file;it needs the file pointer to tell it what file.Thus.P1c = getc(fp).P2places in .UL cthe next character from the file referred to by.UL fp ;it returns.UL EOFwhen it reaches end of file..UL putcis the inverse of.UL getc :.P1putc(c, fp).P2puts the character.UL con the file.UL fp and returns.UL c ..UL getcand.UL putcreturn.UL EOFon error..PPWhen a program is started, three files are opened automatically,and file pointers are provided for them.These files are the standard input,the standard output,and the standard error output;the corresponding file pointers arecalled.UL stdin ,.UL stdout ,and.UL stderr .Normally these are all connected to the terminal,butmay be redirected to files or pipes as described inSection 2.2..UL stdin ,.UL stdoutand.UL stderrare pre-defined in the I/O libraryas the standard input, output and error files;they may be used anywhere an object of type.UL FILE\ *can be.They are constants, however,.ulnotvariables,so don't try to assign to them..PPWith some of the preliminaries out of the way,we can now write.IT wc .The basic design is one that has been foundconvenient for many programs:if there are command-line arguments, they are processed in order.If there are no arguments, the standard inputis processed.This way the program can be used stand-aloneor as part of a larger process..P1#include <stdio.h>main(argc, argv) /* wc: count lines, words, chars */int argc;char *argv[];{ int c, i, inword; FILE *fp, *fopen(); long linect, wordct, charct; long tlinect = 0, twordct = 0, tcharct = 0; i = 1; fp = stdin; do { if (argc > 1 && (fp=fopen(argv[i], "r")) == NULL) { fprintf(stderr, "wc: can't open %s\n", argv[i]); continue; } linect = wordct = charct = inword = 0; while ((c = getc(fp)) != EOF) { charct++; if (c == '\n') linect++; if (c == ' ' || c == '\t' || c == '\n') inword = 0; else if (inword == 0) { inword = 1; wordct++; } } printf("%7ld %7ld %7ld", linect, wordct, charct); printf(argc > 1 ? " %s\n" : "\n", argv[i]); fclose(fp); tlinect += linect; twordct += wordct; tcharct += charct; } while (++i < argc); if (argc > 2) printf("%7ld %7ld %7ld total\n", tlinect, twordct, tcharct); exit(0);}.P2The function.UL fprintfis identical to.UL printf ,save that the first argument is a file pointerthat specifies the file to bewritten..PPThe function.UL fcloseis the inverse of.UL fopen ;it breaks the connection between the file pointer and the external namethat was established by.UL fopen ,freeing thefile pointer for another file.Since there is a limit on the numberof filesthat a program may have open simultaneously,it's a good idea to free things when they are no longer needed.There is also another reason to call.UL fclose on an output file\(em it flushes the bufferin which.UL putcis collecting output..UL fclose \& (is called automatically for each open filewhen a program terminates normally.).NH 2Error Handling \(em Stderr and Exit.PP.UL stderris assigned to a program in the same way that.UL stdinand.UL stdoutare.Output written on .UL stderrappears on the user's terminaleven if the standard output is redirected..IT wcwrites its diagnostics on.UL stderrinstead of.UL stdoutso that if one of the files can'tbe accessed for some reason,the messagefinds its way to the user's terminal instead of disappearingdown a pipelineor into an output file..PPThe program actually signals errors in another way,using the function.UL exit to terminate program execution.The argument of.UL exitis available to whatever processcalled it (see Section 6),so the success or failureof the program can be tested by another programthat uses this one as a sub-process.By convention, a return value of 0signals that all is well;non-zero values signal abnormal situations..PP.UL exititselfcalls.UL fclosefor each open output file,to flush out any buffered output,then callsa routine named.UL _exit .The function.UL _exitcauses immediate termination without any buffer flushing;it may be called directly if desired..NH 2Miscellaneous I/O Functions.PPThe standard I/O library provides several other I/O functionsbesides those we have illustrated above..PPNormally output with.UL putc ,etc., is buffered (except to.UL stderr );to force it out immediately, use.UL fflush(fp) ..PP.UL fscanfis identical to.UL scanf ,except that its first argument is a file pointer(as with.UL fprintf )that specifies the file from which the input comes;it returns.UL EOFat end of file..PPThe functions.UL sscanfand.UL sprintfare identical to.UL fscanfand.UL fprintf ,except that the first argument names a character stringinstead of a file pointer.The conversion is done from the stringfor .UL sscanf and into it for.UL sprintf ..PP.UL fgets(buf,\ size,\ fp)copies the next line from.UL fp ,up to and including a newline,into .UL buf ;at most.UL size-1characters are copied;it returns.UL NULLat end of file..UL fputs(buf,\ fp)writes the string in.UL bufonto file.UL fp ..PPThe function.UL ungetc(c,\ fp)``pushes back'' the character.UL conto the input stream.UL fp ;a subsequent call to.UL getc ,.UL fscanf ,etc.,will encounter .UL c .Only one character of pushback per file is permitted.
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -