Chapter 10: Document
The basic concept of the file file so-called "file" refers to an ordered collection of a set of related data. This data set has a name called file name. In fact, in the previous chapters we have used files many times, such as source files, target files, executables, library files (header files), etc. The file is usually on the external medium (such as a disk, etc.), which is transferred in memory during use. Different from different perspectives can be different from the files. From the user's point of view, the file can be divided into ordinary files and device files. Ordinary file refers to a ordered data set residing on a disk or other external medium, which can be a source file, a target file, an executable program; or a set of raw data to be input, or a set of output result. For source files, target files, executables can be called program files, which can be referred to as data files for input and output data. The device file refers to various external devices associated with the host, such as a display, printer, keyboard, and the like. In the operating system, the external device is also asked as a file to manage, and the input, the output is equivalent to reading and writing of the disk file. Typically define the display as a standard output file, in general, the information is displayed on the screen is output to the standard output file. As the Printf used earlier, the PUTCHAR function is such an output. Keyboards are typically specified for a standard input file, and input from the keyboard means entering data from a standard input file. SCANF, getChar function belongs to such input. From the way of file coding, files can be divided into ASCII code files and binary code files. The ASCII file is also known as a text file, which is stored in the disk, and each character corresponds to one byte, which is used to store the corresponding ASCII code. For example, the storage form of number 5678 is: ASC code: 00110101 00110110 00110111 0011000 ↓ ↓ ↓ 10 feed code: 5 6 7 8 Total 4 bytes. The ASCII code file can be displayed on the screen, such as the source file is an ASCII file, with the DOS command Type to display the contents of the file. Since it is displayed in characters, you can read the contents of the file. Binary files are stored in binary encoding methods. For example, the number of storage forms of 5678 is: 00010110 00101110 Only two bytes. Although binary files can also be displayed on the screen, its content cannot be read. The C system is in handling these files, and it is not distinguished, which is regarded as a character stream, and is processed by byte. The start and end of the input / output character stream is only controlled by the program and is not controlled by the physical symbol (such as the carriage. Therefore, this file is also called "streaming file". This chapter discusses various operations such as opening, closing, reading, writing, and positioning of flow files. The file pointer points to a file with a pointer variable in the C language, which is called a file pointer. The files you refer to the files can be made in various operations. Defining the general form of the file pointer: file * pointer variable identifier; where the file should be uppercase, it is actually a structure defined by the system, which contains information such as file name, file status, and file current location. Don't care about the details of the File structure when writing a source program. For example: file * fp; indicates that the FP is a pointer variable to the File structure. You can find the structural variable of a file information through the FP, and then find the file according to the information provided by the structural variable, and implement the file. It is customary to call the FP as a pointer to a file. The open and closing files of the file are turned on before reading and writing, and the use is to be turned off. The so-called open file is actually a variety of information for establishing a file, and makes the file pointer to the file for other operations. The shutdown file is disconnected between the pointer and the file, or the file is prohibited. In the C language, the file operation is done by the library function.
The main file operation functions will be introduced in this chapter. The file open function fopen function is used to open a file, the general form of the call is: File pointer name = fopen (file name, using file mode) where "file pointer name" must be illustrated as a file type pointer variable, "File Name" is the file name that is opened. "Using file mode" refers to the type and operational requirements of the file. "File Name" is a string constant or a string array. For example: file * fp; fp = ("File A", "R"); its meaning is to open the file file a in the current directory, only "read" operation is allowed, and the FP points to the file. Another example: file * fphzkfphzk = ("C: // HZK16 '," RB ") It is whose meaning is to open the file HZK16 in the root directory of the C drive disk, which is a binary, which is only allowed to perform read operations in binary. The first representation of the second anti-slant line "//", the second represents the root directory. There are 12 ways to use the file, and their symbols and meaning are given below. File usage meaning "RT "Read-only opens a text file, only allow reading data" WT "only writes to open or create a text file, only allowing writing data" AT "to add a text file, and write data" RB "on the end of the file, only open one Binary file, only allow reading data "WB" only written or create a binary file, only allowing writing data "ab" to add a binary file, and write data "RT " in the file end data "RT " to open a text file, allow reading Write "WT " read and write open or create a text file, allow reading and writing "AT " to open a text file, allow reading, or add data "RB " to read a binary file, allow reading and write "WB " reads and writes to open or create a binary, allow reading and writing "AB " to open a binary file, allow reading, or add data in the file to the following description: 1. File usage Made from R, W, A, T, B, Six characters, the meaning of each character is: R (read): Read W (WRITE): Write a (append): Add T (Text): Text file, It can be omitted whether b (banary): Binary : Read and write 2. When you use "R" to open a file, the file must already exist, and can only read it from this file .3. Use "w" to open The file can only be written to the file. If the file does not exist, the file is established with the specified file name. If the open file already exists, the file is deleted, rebuild a new file .4. Add new information to an existing file, you can only open the file with "a". But this file must be existing, otherwise it will be wrong .5. When you open a file, if an error, FOPEN will return A null pointer value NULL. This information can be used in the program to discriminate whether the operation of opening the file is completed and processed accordingly.
So open the files frequently: IF ((fp = fopen ("C: // HZK16", "RB") == null) {Printf ("/ Nerror On open c: // hzk16 file!"); Getch (); EXIT (1);} The meaning of this program is that if the pointer returns is empty, it means that the hizk16 file in the root directory cannot be opened, then the prompt information "Error ON Open C: / Hzk16File!" The function of the next line getch () is a character from the keyboard, but is not displayed on the screen. Here, the role of this line is waiting, only the program continues to execute when the user is knocking from the keyboard, so the user can take this Waiting time reading error message. After the key is keys to execute the exit (1) exit program. 6. When you read a text file into memory, you should convert the ASCII code into a binary code, and the file is written in text to write a disk, Convert binary code to the ASCII code, so the reading and writing of text files takes more conversion time. This conversion does not exist for the reading and writing of binary files. 7. Standard input file (keyboard), standard output file (display), Standard error output (error message) is opened by the system, can be used directly. File Close Function Fclose File Once used, the application closes the file function to avoid the file to avoid the data loss of the file. The general form of thefclose function call is : Fclose (file pointer); for example: fclose (fp); When the FCLOSE (FP) is normal, the FCLOSE function return value is 0. If returns a non-zero value indicates that there is an error occurred. The read and write to the file is written and written for files. The most common file operation. Functions for multiple files are provided in C language: • Character read and write functions: FGETC and FPUTC · String read and write functions: fgets and fputs · Data block read / write functions: freed and fwrite · Format read and write functions: FSCANF and FPRINF are introduced below. Use the above functions to include header file stdio.h. Character read and write functions FGETC and FPUTC character read and write functions are read and write functions in characters (bytes). Each time you can read or write a character from a file. 1. The function of the read character function fgetc fgetc function is to read a character from the specified file, the function call is: character variable = fgetc (file pointer) , For example: CH = FGETC (FP); its meaning is to read a character from the open file fp and send it to the CH. With the following description for the FGETC function: 1. In the FGETC function call, read The file must be opened by reading or reading. 2. The result of reading characters can also be assigned to character variables, for example: fg ETC (FP); but the read characters cannot be saved. 3. There is a position pointer inside the file. The current read and write byte used to point to the file. When the file is opened, the pointer always points to the first byte of the file. After using the FGETC function, the position pointer will move backward one byte. Therefore, the FGETC function can be used for multiple times, read multiple characters. It should be noted that the file pointer and the location of the file inside the file are not a matter. The file pointer is pointing to the entire file, which must be defined in the program, and the value of the file pointer is unchanged as long as it is not re-assigned. The location pointer inside the file is used to indicate the current read and write location inside the file, each read, the pointer moves backward, it does not need to be defined in the program, but is automatically set by the system.
[Example 10.1] Read file E10-1.c, output on the screen. #include main () {file * fp; char ch; if ((fp = fopen ("e10_1.c", "RT")) == null) {Printf ("Cannot Open File Strike Any Key EXIT! "); getCH (); exit (1);} ch = fgetc (fp); while (ch! = EOF) {PUTCHAR (CH); ch = fgetc (fp);} fclose (fp);} The functionality of the case is to read characters one by one from the file and display it on the screen. The program defines the file pointer FP to read the text file to open the file "E10_1.c" and cause the FP to the file. If you open a file error, give a prompt and exit the program. The program 12 first reads a character, and then enter the loop. As long as the character read is not the file end flag (one end flag EOF at each file), the character is displayed on the screen, and then read into the next character. Each read once, the position inside the file indicates a character, and the pointer points to EOF when the file ends. Execute this program will display the entire file. Second, the function of the write character FPUTC FPUTC function is to write a character written to the specified file, the function call is: FPUTC (word symbol, file pointer); where the amount of characters to be written can be character constant or variable For example: FPUTC ('a', fp); its meaning is to write character A to the file pointed to by the FP. For the use of the FPUTC function, you should also explain the few points: 1. The file written can be opened, write, read, write, add mode open, write an existing file content when using write or read and write mode, will clear the original file content Write characters from the beginning of the file. If you need to keep the original file content, you want to write the characters to be stored at the end of the file, you must open the file in an additional manner. If the file written does not exist, the file is created. 2. For each of the characters, the internal location of the file will move one byte backward. 3. The FPUTC function has a return value. If the write is successful, returns a word, otherwise returns an EOF. This can be used to determine whether the write is successful. [Example 10.2] Enter a line from the keyboard to write a file, and then read the file content on the screen. #include main () {file * fp; char ch; if ((fp = fopen ("string", "wt ")) == null) {Printf ("Cannot Open File Strike Any KEY EXIT! "); getCH (); exit (1);} Printf (" INPUT A String: / N "); ch = getchar (); while (ch! = '/ n') {FPUTC (CH, FP); CH = getChar ();} ref (fp); ch = fgetc (fp); while (ch! = EOF) {PUTCHAR (CH); CH = fgetc (fp);} printf ("/ n"); fclose (FP ) The sixth line in the program opens the file string in the way of reading and writing text files. Procedure 13th line After reading a character from the keyboard, enter the loop. When the read characters are not a carriage return, the character is written into the file, and then continue to read the next character from the keyboard. For each character, the file internal location points to move one byte backward. After writing, the pointer has pointed to the end of the file.
To read the file from the head, you must move the pointer to the file header, and the procedure 19th REWIND function is used to move the internal position pointer of the file finger from the FP to the file header. Rows 20 to 25 are used to read a line of content in the file. [Example 10.3] For the files identified by the previous file name in the command line parameter, copy it to the file name identifier, such as only one file name in the command line, writes the file to the standard output file (display) . #include main (int Argc, char * argv []) {file * fp1, * fp2; char ch; if (argc == 1) {Printf ("Have Not Enter File Name Strike Any Key Exit" ); getCH (); exit (0);} = = ((fp1 = fopen (Argv [1], "RT")) == null) {Printf ("canNot open% S / N", argv [1]) GetCH (); exit (1);} if (argc == 2) fp2 = stdout; else if ((fp2 = fopen (argv [2], "wt ")) == null) {Printf ("Cannot Open % S / N ", Argv [1]); getCH (); exit (1);} while ((ch = fgetc (fp1))! = EOF) FPUTC (CH, FP2); fclose (fp1); fclose FP2);} This program is the main function of the belt. Two files fp1 and fp2 are defined in the program, pointing to the files given in the command line parameters, respectively. If the file name is not given in the command line parameter, the prompt information is given. The 18th line of the program means that if only one file name is given, the FP2 points to the standard output file (ie display). The procedure 25 rows to 28 lines of cyclic statements are sent to the file 2 in the read file 1. Run again, a file name (file established by Example 10.2) is given, so output to the standard output file stdout, which is displayed on the display. The third run, give two file names, so read the contents in the String, write to OK. You can use the DOS command TYPE to display OK content: String read and write functions fgets and FPUTS 1. The function of the read string function fgets function is to read a string into the character array from the specified file. The function call is: fgets The character number group name, n, file pointer); N is a positive integer. Indicates that the string read from the file does not exceed N-1 characters. After the last character read, add the string end flag '/ 0'. For example: FGETS (STR, N, FP); meaning is to read the N-1 character sent in the character array STR from the file referred to in the FP. [Example 10.4] A string containing 10 characters is read from the E10_1.C file.
#include main () {file * fp; char STR [11]; IF ((fp = fopen ("e10_1.c", "RT")) == null) {Printf ("Cannot Open File Strike any key exit! "); getCH (); exit (1);} fgets (STR, 11, fp); Printf ("% s ", str); fclose (fp);} This example defines an array of characters A total of 11 bytes, after opening the file E101.c in reading a text file, and reads 10 characters from the STR array, and will add '/ 0' within the last unit, then display on the screen. Output STR array. The ten characters output are the top ten characters of the Example 10.1 program. There are two descriptions for the FGETS function: 1. Before reading the N-1 characters, if you encounter a chart or EOF, the readout ends. 2. The FGETS function also has a return value, and its return value is the first address of the character array. Second, the function of the write string function The function of the FPUTSFPUTS function is to write a string to the specified file, which is: fputs (string, file pointer) where the string can be a string, or a character number group name, Or pointer variables, such as fputs ("abcd", fp); its meaning is to write strings "abcd" into the file referred to in the FP. [Example 10.5] Add a string in the file String established in Example 10.2. #include main () {file * fp; char ch, st [20]; if ((fp = fopen ("string", "at ")) == null) {printf ("Cannot Open file Strike any key exit! "); getch (); exit (1);} Printf (" Input A String: / N "); Scanf ("% S ", ST); FPUTS (ST, FP); REWIND (FP) ); ch = fgetc (fp); while (ch! = EOF) {PUTCHAR (CH); CH = fgetc (fp);} printf ("/ n"); fclose (fp);} This example requires files in String files The end is written in a string, so open the file string in the way of the program's sixth line to add a text file. Then enter the string and write the string into the file string with the FPUTS function. Move the file internal location pointer to the file in the program 15 row. Then enter the cycle one by one to display all the contents in the current file. Data block read and write functions FREAD and FWRITE C are also provided to read and write functions for whole blocks. Can be used to read and write a set of data, such as an array element, a structural variable value, etc. The general form of reading data block function call is: Fread (Buffer, Size, Count, FP); Write data block function calls are: fwrite (buffer, size, count, fp); where buffer is a pointer, in FREAD In the function, it represents the first address of the input data. In the fwrite function, it represents the first address of the output data. Size represents the number of bytes of data blocks. COUNT indicates the number of data blocks to read and written. FP represents the file pointer.
For example: FREAD (FA, 4, 5, FP); its meaning is from the file referred to in the FP, each reads 4 bytes (a real number) into the real group FA, continuously reading 5 times, reading 5 Real numbers to fa. [Example 10.6] Enter two student data from the keyboard, written in a file, and then read the data of the two student is displayed on the screen. #include struct stu {char name [10]; int Num; int Age; char addr [15];} Boya [2], Boyb [2], * PP, * QQ; main () {file * fp; char ch; INT i; pp = boya; qq = boyb; if ((fp = fopen ("stu_list", "WB "))) == null) {Printf ("Cannot Open File Strike any key exit!" ); getCH (); exit (1);} printf ("/ ninput data / n"); for (i = 0; i <2; i , pp ) scanf ("% s% D% D% s", PP-> Name, & PP-> Num, & PP-> Age, PP-> Addr); PP = Boya; FWRITE (PP, SIZEOF (Struct Stu), 2, FP); Rewind (fp); FREAD (QQ, Sizeof (STRUCT STU), 2, FP); Printf ("/ n / nName / TNUMBER AGE AGDR / N"); for (i = 0; i <2; i , QQ ) Printf ("% S / T% 5D% 7D% S / N ", QQ-> Name, QQ-> Num, QQ-> AGE, QQ-> AddR); Fclose (fp);} This program defines a structure STU, indicating two structural arrays Boya And BOYB and two structural pointers variables PP and QQ. PP points to BOYA, QQ points to BOYB. Procedure 16th line opens the binary "stu_list" by reading and writing, enters the two student data, write into the file, then move the file internal position pointer to the file, read two student data, on the screen display. Format the read and write function FSCANF and FPRINTFFSCANF functions, the FPRINTF function is similar to the functionality of the Scanf and Printf functions used in front, all formatted read and write functions. The difference between the two is that the FSCANF function and the read and write object of the FPRINTF function are not a keyboard and a display, but a disk file. The call format of these two functions is: fscanf (file pointer, format string, input table column); FPRINTF (file pointer, format string, output list); for example: fscanf (FP, "% D% S", & I, s); FPRINTF (FP, "% D% C", J, CH); the problem with FSCANF and FPRINTF functions can also be completed. The modified program is shown in Example 10.7.
[Example 10.7] #include struct stu {char name [10]; int Num; int Age; char addr [15];} Boya [2], Boyb [2], * PP, * QQ; main () {File * fp; char ch; INT i; pp = boya; QQ = boyb; if ((fp = fopen ("stu_list", "WB "))) == null) {Printf ("Cannot Open File Strike Any Key Exit! "); getCh (); exit (1);} Printf (" / ninput data / n "); for (i = 0; i <2; i , pp ) scanf ("% s% D% D) % S ", PP-> Name, & PP-> Num, & PP-> AGE, PP-> AddR); PP = Boya; for (i = 0; i <2; i , PP ) fprintf (fp,"% s % D% D% S / N ", PP-> Name, PP-> Num, PP-> AGE, PP-> Addr); ReWind (fp); for (i = 0; i <2; i , QQ ) FSCANF (FP, "% S% D% D% S / N", QQ-> Name, & QQ-> Num, & QQ-> AGE, QQ-> AddR); Printf ("/ N / NNAME / TNUMBER AGE Addr / N "); QQ = Boyb; for (i = 0; i <2; i , QQ ) Printf ("% S / T% 5D% 7D% S / N ", QQ-> Name, QQ-> Num, QQ -> AGE, QQ-> Addr; Fclose (fp);} Compared to Example 10.6, the FSCANF and FPRINTF functions in this program can only read and write a structural array element each time, so it uses a loop statement to read and write all arrays. element. Also pay attention to the pointer variable PP, QQ has changed their value due to the loop, so the first address of the array is re-imparted in the 25th and 32 lines of the program. File random reading The previous introduction to the read and write mode of the file is sequential, that is, the read and write file can only be read from the beginning, sequential read and write each data. However, in practice, you often ask for a certain specified part in read-only write files. In order to solve this problem, the location pointer inside the mobile file is moved to the location that needs to be read, and then reads and writes, this read and write is called random reading. The key to achieving random reading is to move the position pointer as required, which is called the file positioning. File Location Mobile File Internal Location Pointer There are two, namely the REWIND function and the FSEEK function. The REWIND function has been used several times, and its call form is: Rewind (file pointer); its function is to move the location pointer inside the file to the file. The following mainly introduces the FSEEK function. The FSEEK function is used to move the file internal location pointer, which is: fseek (file pointer, displacement, starting point); where: "File Pointer" points to the mobile file. "Displacement" means that the number of bytes moved, requiring the displacement amount to be long data so that it will not be wrong when the file length is greater than 64kb. When the displacement is indicated by a constant, it is required to add "L". "Start Point" indicates where to start calculating the bitmine, three specified starting points: file first, current location and file end. Its representation is shown in Table 10.2.
The starting point represents the symbol number - ──────────────────- Document SEEK-SET 0 Current location SEEK-CUR 1 file end SEEK-END 2 For example: FSeek (FP, 100L, 0); its meaning is to move the position pointer to the first 100 bytes of files. It is also shown that the FSEEK function is generally used for binary files. In the text file, due to the conversion, the location that is often calculated will occur. The random read and write of the file After moving the position pointer, you can read and write any of the read and write functions previously described. Since it is generally read and written a data block, the FREAD and FWRITE functions are commonly used. The following uses an example to explain the random read and write of the file. [Example 10.8] The data of the second student is read in the Student Document STU LIST. #include struct stu {char name [10]; int Num; int Age; char addr [15];} BOY, * QQ; main () {file * fp; char ch; int i = 1; QQ = & boy; if ((fp = fopen ("stu_list", "RB"))) == null) {Printf ("Cannot Open File Strike any key exit!); getCh (); exit (1);} (fp); FSeek (FP, I * SizeOf (Struct Stu), 0); FREAD (QQ, SIZEOF (Struct Stu), 1, FP); Printf ("/ N / NNAME / TNUMBER AGE ADDR / N"); Printf ("% S / T% 5d% 7D% S / N", QQ-> Name, QQ-> Num, QQ-> AGE, QQ-> AddR);} The file STU_LIST has been established by the program 10.6, this The program reads out the data of the second student with a randomly read method. Defining BOY is the STU type variable, QQ is a pointer to BOY. Open the file in a binary file, the program 22th line moves the file position pointer. Where the I value is 1, indicates the length of the STU type from the file header, and then read out is the data of the second student. The file detection function commonly used in the file detection function C language has the following. First, the file end detection function feOf function call format: FeOf (file pointer); function: Determine if the file is in the file end position, if the file ends, the return value is 1, otherwise 0. Second, read and write file error detection functions FERROR function call format: Ferror (file pointer); function: Check if the file is read or written in various input and output functions. If the FERROR return value is 0, it is wrong, otherwise it means wrong. Third, the file error flag and file end flag set 0 function clearrr function call format: Clearerr (file pointer); function: This function is used to clear the error flag and file end flag to make them zero. The C library file C system provides a wealth of system files, called library files, and C library files are divided into two categories. One type is a file called ".h", called header file, in the previous included command We have used many times. In the ".h" file contains information such as constant definition, type definition, macro definition, function prototype, and various compilation selection settings. Another category is a function library, including a target code for various functions, and is called in the program. When a library function is typically called in the program, you want to include the ".h" file where the function prototype is in the call. A total library function is given in the appendix. Alloc.h Description Memory Management Function (Assign, Release, etc.). AskERT.H Defines an Assert debugging macro.
Bios.h Description Call the various functions of the IBM-PC ROM BIOS subroutine. Conio.h describes the various functions of calling the DOS console I / O subroutine. Ctype.h contains a name-class information (such as Isalpha and Toascii, etc.) about character classification and conversion. Dir.h contains structures, macro definitions, and functions related to directory and path. DOS.H defines and describes some constants and functions that MSDOS and 8086 calls. Erron.h defines a mission of the error code. Fcntl.h defines symbol constants when connecting to the Open library. Float.h contains some parameters and functions about floating point operations. Graphics.h describes some of the specific structures of various functions, graphical error codes, and some special structures that are for different colors of different drivers, and functions. IO.H contains the structure and description of the low-level I / O subroutine. Limit.h includes information such as environmental parameters, compilation time limits, number of numbers. Math.h illustrates the mathematical calculation function, and it has also set the HUGE VAL macro to illustrate the special structure used by Matherr and Matherr subroutines. MEM.H illustrates some memory operation functions (most of them are also illustrated in string.h). Process.h Describes the structure of each function, spawn ... and exec ... function of process management. Setjmp.h Defines the JMP BUF type used by longjmp and setjmp functions, indicating these two functions. Share.h defines the parameters of the file sharing function. Signal.h Defines SIG [ZZ (Z] [ZZ)] IGN and SIG [ZZ (Z] [ZZ)] DFL constants, describing both Rajse and Signal. Stdarg.h defines the macro of the read function parameter table. Such as Vprintf, VSCARF functions. STDDEF.H defines some public data types and macros. Stdio.h defines the type and macros defined in the UNIGHAN and RITCHIE in UNIX System V. Standard I / O predefined streams are also defined: stdin, stdout, and stderr, describe the I / O draft program. STDLIB.H illustrates some common subroutines: converted subroutines, search / rank sequence, etc. String.h Description Some string operations and memory operation functions. Sys / stat.h defines some symbol constants used when opening and creating files. SYS / TYPES.H Describes the FTIME function and the TIMEB structure. Sys / time.h defines Type Time [Z] [ZZ)] T. Time.h Defines Time Converter AscTime, LocalTime, and Gmtime 's Structure, CTIME, DIFFTIME, GMTIME, LOCALTIME, and STIME to be used, and provide prototypes of these functions. Value.h defines some important constants, including some constants that depend on the machine hardware and instructions compatible with UNIX System V, including floating point and double precision values. This chapter summary 1. The C system treats the file as a "stream", and is processed by byte. 2. The C file is divided into binary files and ASCII files by encoding. 3. C language, use the file pointer identifies the file, and the file pointer can be obtained when a file is opened. 4. The file must be opened before reading and writing, and the reading and writing must be turned off. 5. Documents can be opened by read-only, write, read, write, and add four operations, and must also specify the type of files to be binary or text files. 6. Files can be read by bytes, strings, and data blocks, and files can also be read and written in the specified format. 7. The location pointer inside the file can indicate the current read and write position, and the pointer can be used to read and write files. Data Collection: Beck Copyright 2002 www.vcok.com, All Rights Reserved
TD {font-size: 9pt}
Body {color: # 000000; Font-size: 9pt; line-height: 150%}
A: Link {color: # 000000; Text-Decoration: none}
A: visited {color: # 000000; Text-Decoration: none}
A: Active {color: # 000000; Text-Decoration: none}
A: Hover {color: # ff0000; text-decoration: underline}
Chapter 10: Document
The basic concept of the file file so-called "file" refers to an ordered collection of a set of related data. This data set has a name called file name. In fact, in the previous chapters we have used files many times, such as source files, target files, executables, library files (header files), etc. The file is usually on the external medium (such as a disk, etc.), which is transferred in memory during use. Different from different perspectives can be different from the files. From the user's point of view, the file can be divided into ordinary files and device files. Ordinary file refers to a ordered data set residing on a disk or other external medium, which can be a source file, a target file, an executable program; or a set of raw data to be input, or a set of output result. For source files, target files, executables can be called program files, which can be referred to as data files for input and output data. The device file refers to various external devices associated with the host, such as a display, printer, keyboard, and the like. In the operating system, the external device is also asked as a file to manage, and the input, the output is equivalent to reading and writing of the disk file. Typically define the display as a standard output file, in general, the information is displayed on the screen is output to the standard output file. As the Printf used earlier, the PUTCHAR function is such an output. Keyboards are typically specified for a standard input file, and input from the keyboard means entering data from a standard input file. SCANF, getChar function belongs to such input. From the way of file coding, files can be divided into ASCII code files and binary code files. The ASCII file is also known as a text file, which is stored in the disk, and each character corresponds to one byte, which is used to store the corresponding ASCII code. For example, the storage form of number 5678 is: ASC code: 00110101 00110110 00110111 0011000 ↓ ↓ ↓ 10 feed code: 5 6 7 8 Total 4 bytes. The ASCII code file can be displayed on the screen, such as the source file is an ASCII file, with the DOS command Type to display the contents of the file. Since it is displayed in characters, you can read the contents of the file. Binary files are stored in binary encoding methods. For example, the number of storage forms of 5678 is: 00010110 00101110 Only two bytes. Although binary files can also be displayed on the screen, its content cannot be read. The C system is in handling these files, and it is not distinguished, which is regarded as a character stream, and is processed by byte. The start and end of the input / output character stream is only controlled by the program and is not controlled by the physical symbol (such as the carriage. Therefore, this file is also called "streaming file". This chapter discusses various operations such as opening, closing, reading, writing, and positioning of flow files. The file pointer points to a file with a pointer variable in the C language, which is called a file pointer. The files you refer to the files can be made in various operations. Defining the general form of the file pointer: file * pointer variable identifier; where the file should be uppercase, it is actually a structure defined by the system, which contains information such as file name, file status, and file current location. Don't care about the details of the File structure when writing a source program. For example: file * fp; indicates that the FP is a pointer variable to the File structure. You can find the structural variable of a file information through the FP, and then find the file according to the information provided by the structural variable, and implement the file. It is customary to call the FP as a pointer to a file. The open and closing files of the file are turned on before reading and writing, and the use is to be turned off. The so-called open file is actually a variety of information for establishing a file, and makes the file pointer to the file for other operations. The shutdown file is disconnected between the pointer and the file, or the file is prohibited. In the C language, the file operation is done by the library function.
The main file operation functions will be introduced in this chapter. The file open function fopen function is used to open a file, the general form of the call is: File pointer name = fopen (file name, using file mode) where "file pointer name" must be illustrated as a file type pointer variable, "File Name" is the file name that is opened. "Using file mode" refers to the type and operational requirements of the file. "File Name" is a string constant or a string array. For example: file * fp; fp = ("File A", "R"); its meaning is to open the file file a in the current directory, only "read" operation is allowed, and the FP points to the file. Another example: file * fphzkfphzk = ("C: // HZK16 '," RB ") It is whose meaning is to open the file HZK16 in the root directory of the C drive disk, which is a binary, which is only allowed to perform read operations in binary. The first representation of the second anti-slant line "//", the second represents the root directory. There are 12 ways to use the file, and their symbols and meaning are given below. File usage meaning "RT "Read-only opens a text file, only allow reading data" WT "only writes to open or create a text file, only allowing writing data" AT "to add a text file, and write data" RB "on the end of the file, only open one Binary file, only allow reading data "WB" only written or create a binary file, only allowing writing data "ab" to add a binary file, and write data "RT " in the file end data "RT " to open a text file, allow reading Write "WT " read and write open or create a text file, allow reading and writing "AT " to open a text file, allow reading, or add data "RB " to read a binary file, allow reading and write "WB " reads and writes to open or create a binary, allow reading and writing "AB " to open a binary file, allow reading, or add data in the file to the following description: 1. File usage Made from R, W, A, T, B, Six characters, the meaning of each character is: R (read): Read W (WRITE): Write a (append): Add T (Text): Text file, It can be omitted whether b (banary): Binary : Read and write 2. When you use "R" to open a file, the file must already exist, and can only read it from this file .3. Use "w" to open The file can only be written to the file. If the file does not exist, the file is established with the specified file name. If the open file already exists, the file is deleted, rebuild a new file .4. Add new information to an existing file, you can only open the file with "a". But this file must be existing, otherwise it will be wrong .5. When you open a file, if an error, FOPEN will return A null pointer value NULL. This information can be used in the program to discriminate whether the operation of opening the file is completed and processed accordingly.
So open the files frequently: IF ((fp = fopen ("C: // HZK16", "RB") == null) {Printf ("/ Nerror On open c: // hzk16 file!"); Getch (); EXIT (1);} The meaning of this program is that if the pointer returns is empty, it means that the hizk16 file in the root directory cannot be opened, then the prompt information "Error ON Open C: / Hzk16File!" The function of the next line getch () is a character from the keyboard, but is not displayed on the screen. Here, the role of this line is waiting, only the program continues to execute when the user is knocking from the keyboard, so the user can take this Waiting time reading error message. After the key is keys to execute the exit (1) exit program. 6. When you read a text file into memory, you should convert the ASCII code into a binary code, and the file is written in text to write a disk, Convert binary code to the ASCII code, so the reading and writing of text files takes more conversion time. This conversion does not exist for the reading and writing of binary files. 7. Standard input file (keyboard), standard output file (display), Standard error output (error message) is opened by the system, can be used directly. File Close Function Fclose File Once used, the application closes the file function to avoid the file to avoid the data loss of the file. The general form of thefclose function call is : Fclose (file pointer); for example: fclose (fp); When the FCLOSE (FP) is normal, the FCLOSE function return value is 0. If returns a non-zero value indicates that there is an error occurred. The read and write to the file is written and written for files. The most common file operation. Functions for multiple files are provided in C language: • Character read and write functions: FGETC and FPUTC · String read and write functions: fgets and fputs · Data block read / write functions: freed and fwrite · Format read and write functions: FSCANF and FPRINF are introduced below. Use the above functions to include header file stdio.h. Character read and write functions FGETC and FPUTC character read and write functions are read and write functions in characters (bytes). Each time you can read or write a character from a file. 1. The function of the read character function fgetc fgetc function is to read a character from the specified file, the function call is: character variable = fgetc (file pointer) , For example: CH = FGETC (FP); its meaning is to read a character from the open file fp and send it to the CH. With the following description for the FGETC function: 1. In the FGETC function call, read The file must be opened by reading or reading. 2. The result of reading characters can also be assigned to character variables, for example: fg ETC (FP); but the read characters cannot be saved. 3. There is a position pointer inside the file. The current read and write byte used to point to the file. When the file is opened, the pointer always points to the first byte of the file. After using the FGETC function, the position pointer will move backward one byte. Therefore, the FGETC function can be used for multiple times, read multiple characters. It should be noted that the file pointer and the location of the file inside the file are not a matter. The file pointer is pointing to the entire file, which must be defined in the program, and the value of the file pointer is unchanged as long as it is not re-assigned. The location pointer inside the file is used to indicate the current read and write location inside the file, each read, the pointer moves backward, it does not need to be defined in the program, but is automatically set by the system.
[Example 10.1] Read file E10-1.c, output on the screen. #include main () {file * fp; char ch; if ((fp = fopen ("e10_1.c", "RT")) == null) {Printf ("Cannot Open File Strike Any Key EXIT! "); getCH (); exit (1);} ch = fgetc (fp); while (ch! = EOF) {PUTCHAR (CH); ch = fgetc (fp);} fclose (fp);} The functionality of the case is to read characters one by one from the file and display it on the screen. The program defines the file pointer FP to read the text file to open the file "E10_1.c" and cause the FP to the file. If you open a file error, give a prompt and exit the program. The program 12 first reads a character, and then enter the loop. As long as the character read is not the file end flag (one end flag EOF at each file), the character is displayed on the screen, and then read into the next character. Each read once, the position inside the file indicates a character, and the pointer points to EOF when the file ends. Execute this program will display the entire file. Second, the function of the write character FPUTC FPUTC function is to write a character written to the specified file, the function call is: FPUTC (word symbol, file pointer); where the amount of characters to be written can be character constant or variable For example: FPUTC ('a', fp); its meaning is to write character A to the file pointed to by the FP. For the use of the FPUTC function, you should also explain the few points: 1. The file written can be opened, write, read, write, add mode open, write an existing file content when using write or read and write mode, will clear the original file content Write characters from the beginning of the file. If you need to keep the original file content, you want to write the characters to be stored at the end of the file, you must open the file in an additional manner. If the file written does not exist, the file is created. 2. For each of the characters, the internal location of the file will move one byte backward. 3. The FPUTC function has a return value. If the write is successful, returns a word, otherwise returns an EOF. This can be used to determine whether the write is successful. [Example 10.2] Enter a line from the keyboard to write a file, and then read the file content on the screen. #include main () {file * fp; char ch; if ((fp = fopen ("string", "wt ")) == null) {Printf ("Cannot Open File Strike Any KEY EXIT! "); getCH (); exit (1);} Printf (" INPUT A String: / N "); ch = getchar (); while (ch! = '/ n') {FPUTC (CH, FP); CH = getChar ();} ref (fp); ch = fgetc (fp); while (ch! = EOF) {PUTCHAR (CH); CH = fgetc (fp);} printf ("/ n"); fclose (FP ) The sixth line in the program opens the file string in the way of reading and writing text files. Procedure 13th line After reading a character from the keyboard, enter the loop. When the read characters are not a carriage return, the character is written into the file, and then continue to read the next character from the keyboard. For each character, the file internal location points to move one byte backward. After writing, the pointer has pointed to the end of the file.
To read the file from the head, you must move the pointer to the file header, and the procedure 19th REWIND function is used to move the internal position pointer of the file finger from the FP to the file header. Rows 20 to 25 are used to read a line of content in the file. [Example 10.3] For the files identified by the previous file name in the command line parameter, copy it to the file name identifier, such as only one file name in the command line, writes the file to the standard output file (display) . #include main (int Argc, char * argv []) {file * fp1, * fp2; char ch; if (argc == 1) {Printf ("Have Not Enter File Name Strike Any Key Exit" ); getCH (); exit (0);} = = ((fp1 = fopen (Argv [1], "RT")) == null) {Printf ("canNot open% S / N", argv [1]) GetCH (); exit (1);} if (argc == 2) fp2 = stdout; else if ((fp2 = fopen (argv [2], "wt ")) == null) {Printf ("Cannot Open % S / N ", Argv [1]); getCH (); exit (1);} while ((ch = fgetc (fp1))! = EOF) FPUTC (CH, FP2); fclose (fp1); fclose FP2);} This program is the main function of the belt. Two files fp1 and fp2 are defined in the program, pointing to the files given in the command line parameters, respectively. If the file name is not given in the command line parameter, the prompt information is given. The 18th line of the program means that if only one file name is given, the FP2 points to the standard output file (ie display). The procedure 25 rows to 28 lines of cyclic statements are sent to the file 2 in the read file 1. Run again, a file name (file established by Example 10.2) is given, so output to the standard output file stdout, which is displayed on the display. The third run, give two file names, so read the contents in the String, write to OK. You can use the DOS command TYPE to display OK content: String read and write functions fgets and FPUTS 1. The function of the read string function fgets function is to read a string into the character array from the specified file. The function call is: fgets The character number group name, n, file pointer); N is a positive integer. Indicates that the string read from the file does not exceed N-1 characters. After the last character read, add the string end flag '/ 0'. For example: FGETS (STR, N, FP); meaning is to read the N-1 character sent in the character array STR from the file referred to in the FP. [Example 10.4] A string containing 10 characters is read from the E10_1.C file.
#include main () {file * fp; char STR [11]; IF ((fp = fopen ("e10_1.c", "RT")) == null) {Printf ("Cannot Open File Strike any key exit! "); getCH (); exit (1);} fgets (STR, 11, fp); Printf ("% s ", str); fclose (fp);} This example defines an array of characters A total of 11 bytes, after opening the file E101.c in reading a text file, and reads 10 characters from the STR array, and will add '/ 0' within the last unit, then display on the screen. Output STR array. The ten characters output are the top ten characters of the Example 10.1 program. There are two descriptions for the FGETS function: 1. Before reading the N-1 characters, if you encounter a chart or EOF, the readout ends. 2. The FGETS function also has a return value, and its return value is the first address of the character array. Second, the function of the write string function The function of the FPUTSFPUTS function is to write a string to the specified file, which is: fputs (string, file pointer) where the string can be a string, or a character number group name, Or pointer variables, such as fputs ("abcd", fp); its meaning is to write strings "abcd" into the file referred to in the FP. [Example 10.5] Add a string in the file String established in Example 10.2. #include main () {file * fp; char ch, st [20]; if ((fp = fopen ("string", "at ")) == null) {printf ("Cannot Open file Strike any key exit! "); getch (); exit (1);} Printf (" Input A String: / N "); Scanf ("% S ", ST); FPUTS (ST, FP); REWIND (FP) ); ch = fgetc (fp); while (ch! = EOF) {PUTCHAR (CH); CH = fgetc (fp);} printf ("/ n"); fclose (fp);} This example requires files in String files The end is written in a string, so open the file string in the way of the program's sixth line to add a text file. Then enter the string and write the string into the file string with the FPUTS function. Move the file internal location pointer to the file in the program 15 row. Then enter the cycle one by one to display all the contents in the current file. Data block read and write functions FREAD and FWRITE C are also provided to read and write functions for whole blocks. Can be used to read and write a set of data, such as an array element, a structural variable value, etc. The general form of reading data block function call is: Fread (Buffer, Size, Count, FP); Write data block function calls are: fwrite (buffer, size, count, fp); where buffer is a pointer, in FREAD In the function, it represents the first address of the input data. In the fwrite function, it represents the first address of the output data. Size represents the number of bytes of data blocks. COUNT indicates the number of data blocks to read and written. FP represents the file pointer.
For example: FREAD (FA, 4, 5, FP); its meaning is from the file referred to in the FP, each reads 4 bytes (a real number) into the real group FA, continuously reading 5 times, reading 5 Real numbers to fa. [Example 10.6] Enter two student data from the keyboard, written in a file, and then read the data of the two student is displayed on the screen. #include struct stu {char name [10]; int Num; int Age; char addr [15];} Boya [2], Boyb [2], * PP, * QQ; main () {file * fp; char ch; INT i; pp = boya; qq = boyb; if ((fp = fopen ("stu_list", "WB "))) == null) {Printf ("Cannot Open File Strike any key exit!" ); getCH (); exit (1);} printf ("/ ninput data / n"); for (i = 0; i <2; i , pp ) scanf ("% s% D% D% S", PP-> Name, & PP-> Num, & PP-> Age, PP-> Addr); PP = Boya; FWRITE (PP, SIZEOF (Struct Stu), 2, FP); Rewind (fp); FREAD (QQ, Sizeof (STRUCT STU), 2, FP); Printf ("/ n / nName / TNUMBER AGE AGDR / N"); for (i = 0; i <2; i , QQ ) Printf ("% S / T% 5D% 7D% S / N ", QQ-> Name, QQ-> Num, QQ-> AGE, QQ-> AddR); Fclose (fp);} This program defines a structure STU, indicating two structural arrays Boya And BOYB and two structural pointers variables PP and QQ. PP points to BOYA, QQ points to BOYB. Procedure 16th line opens the binary "stu_list" by reading and writing, enters the two student data, write into the file, then move the file internal position pointer to the file, read two student data, on the screen display. Format the read and write function FSCANF and FPRINTFFSCANF functions, the FPRINTF function is similar to the functionality of the Scanf and Printf functions used in front, all formatted read and write functions. The difference between the two is that the FSCANF function and the read and write object of the FPRINTF function are not a keyboard and a display, but a disk file. The call format of these two functions is: fscanf (file pointer, format string, input table column); FPRINTF (file pointer, format string, output list); for example: fscanf (FP, "% D% S", & I, s); FPRINTF (FP, "% D% C", J, CH); the problem with FSCANF and FPRINTF functions can also be completed. The modified program is shown in Example 10.7.
[Example 10.7] #include struct stu {char name [10]; int Num; int Age; char addr [15];} Boya [2], Boyb [2], * PP, * QQ; main () {File * fp; char ch; INT i; pp = boya; QQ = boyb; if ((fp = fopen ("stu_list", "WB "))) == null) {Printf ("Cannot Open File Strike Any Key Exit! "); getCh (); exit (1);} Printf (" / ninput data / n "); for (i = 0; i <2; i , pp ) scanf ("% s% D% D) % S ", PP-> Name, & PP-> Num, & PP-> AGE, PP-> AddR); PP = Boya; for (i = 0; i <2; i , PP ) fprintf (fp,"% s % D% D% S / N ", PP-> Name, PP-> Num, PP-> AGE, PP-> Addr); ReWind (fp); for (i = 0; i <2; i , QQ ) FSCANF (FP, "% S% D% D% S / N", QQ-> Name, & QQ-> Num, & QQ-> AGE, QQ-> AddR); Printf ("/ N / NNAME / TNUMBER AGE Addr / N "); QQ = Boyb; for (i = 0; i <2; i , QQ ) Printf ("% S / T% 5D% 7D% S / N ", QQ-> Name, QQ-> Num, QQ -> AGE, QQ-> Addr; Fclose (fp);} Compared to Example 10.6, the FSCANF and FPRINTF functions in this program can only read and write a structural array element each time, so it uses a loop statement to read and write all arrays. element. Also pay attention to the pointer variable PP, QQ has changed their value due to the loop, so the first address of the array is re-imparted in the 25th and 32 lines of the program. File random reading The previous introduction to the read and write mode of the file is sequential, that is, the read and write file can only be read from the beginning, sequential read and write each data. However, in practice, you often ask for a certain specified part in read-only write files. In order to solve this problem, the location pointer inside the mobile file is moved to the location that needs to be read, and then reads and writes, this read and write is called random reading. The key to achieving random reading is to move the position pointer as required, which is called the file positioning. File Location Mobile File Internal Location Pointer There are two, namely the REWIND function and the FSEEK function. The REWIND function has been used several times, and its call form is: Rewind (file pointer); its function is to move the location pointer inside the file to the file. The following mainly introduces the FSEEK function. The FSEEK function is used to move the file internal location pointer, which is: fseek (file pointer, displacement, starting point); where: "File Pointer" points to the mobile file. "Displacement" means that the number of bytes moved, requiring the displacement amount to be long data so that it will not be wrong when the file length is greater than 64kb. When the displacement is indicated by a constant, it is required to add "L". "Start Point" indicates where to start calculating the bitmine, three specified starting points: file first, current location and file end. Its representation is shown in Table 10.2.
The starting point represents the symbol number - ──────────────────- Document SEEK-SET 0 Current location SEEK-CUR 1 file end SEEK-END 2 For example: FSeek (FP, 100L, 0); its meaning is to move the position pointer to the first 100 bytes of files. It is also shown that the FSEEK function is generally used for binary files. In the text file, due to the conversion, the location that is often calculated will occur. The random read and write of the file After moving the position pointer, you can read and write any of the read and write functions previously described. Since it is generally read and written a data block, the FREAD and FWRITE functions are commonly used. The following uses an example to explain the random read and write of the file. [Example 10.8] The data of the second student is read in the Student Document STU LIST. #include struct stu {char name [10]; int Num; int Age; char addr [15];} BOY, * QQ; main () {file * fp; char ch; int i = 1; QQ = & boy; if ((fp = fopen ("stu_list", "RB"))) == null) {Printf ("Cannot Open File Strike any key exit!); getCh (); exit (1);} (fp); FSeek (FP, I * SizeOf (Struct Stu), 0); FREAD (QQ, SIZEOF (Struct Stu), 1, FP); Printf ("/ N / NNAME / TNUMBER AGE ADDR / N"); Printf ("% S / T% 5d% 7D% S / N", QQ-> Name, QQ-> Num, QQ-> AGE, QQ-> AddR);} The file STU_LIST has been established by the program 10.6, this The program reads out the data of the second student with a randomly read method. Defining BOY is the STU type variable, QQ is a pointer to BOY. Open the file in a binary file, the program 22th line moves the file position pointer. Where the I value is 1, indicates the length of the STU type from the file header, and then read out is the data of the second student. The file detection function commonly used in the file detection function C language has the following. First, the file end detection function feOf function call format: FeOf (file pointer); function: Determine if the file is in the file end position, if the file ends, the return value is 1, otherwise 0. Second, read and write file error detection functions FERROR function call format: Ferror (file pointer); function: Check if the file is read or written in various input and output functions. If the FERROR return value is 0, it is wrong, otherwise it means wrong. Third, the file error flag and file end flag set 0 function clearrr function call format: Clearerr (file pointer); function: This function is used to clear the error flag and file end flag to make them zero. The C library file C system provides a wealth of system files, called library files, and C library files are divided into two categories. One type is a file called ".h", called header file, in the previous included command We have used many times. In the ".h" file contains information such as constant definition, type definition, macro definition, function prototype, and various compilation selection settings. Another category is a function library, including a target code for various functions, and is called in the program. When a library function is typically called in the program, you want to include the ".h" file where the function prototype is in the call. A total library function is given in the appendix. Alloc.h Description Memory Management Function (Assign, Release, etc.). AskERT.H Defines an Assert debugging macro.