1.2 file input and output function keyboard, monitor, printer, disk drive and other logical devices, the input and output can be through the file management method to complete. And the most used in programming to be considered disk files, so this section is mainly disk files, specifically, the Turbo C2.0 provides the file operation functions, of course, these file operation function is also suitable for non-disk files. In addition, the Turbo C2.0 provides two types of functions for files. A class of standard file functions are also called buffer-type file functions, which are defined by the ANSI standard function; There is also a class called non-standard file functions, also known as non-buffered file functions. This type of function is first common to UNIX operating systems, but today's operating systems with the ms-dos3.0 version number are also available. The following are described separately. 1.2.1 Standard file functions The standard file functions mainly include the opening, closing, reading and writing functions of the file. Unlike basic and Fortran, which have sequential files and random files, they should be determined in different ways when opened. The Turbo C2.0 does not differentiate between the two files, but provides two sets of functions, namely sequential read and write functions and random read and write functions. The opening and closing of a file no matter what file is used before and after use, it is necessary to open and close, because the operating system for the same time the number of open files is limited, DOS operating system, can be on the device. SYS defines the number of files to open at the same time n (defined with files=n). where n is the number of files that can be opened at the same time, generally n<=20. Therefore, before using the file, you should open the file before you can access the information in it. Need to close after use, or there will be some unexpected errors. The Turbo C2.0 provides functions for opening and closing files. 1. The fopen () function fopen function is used to open a file in a format called:FILE*fopen (Char *filename, *type); Before introducing this function, let's take a look at the following knowledge. (1) Stream and file streams and files differ in the Turbo C2.0, and the turbo C2.0 provides a layer of abstraction between the programmer and the device being interviewed, called a "stream", and the detailed actual device is called a file. A stream is a logical device that has the same behavior. As a result, the functions used to write disk files are the same as can be used for printer writing. There are two kinds of streams in the Turbo C2.0: text stream and binary (binary stream). For a disk, it is a text file and a binary file. The software is designed to make it easy for readers to understand the Turbo C2.0 language without the special distinction between convection and documentation. (2) Document pointer file is actually a new data type. It is a collection of basic data types for the turbo C2.0, called struct pointers. The concept of the structure will be described in section fourth, where the file is simply understood as a data structure that contains information about the management of the file, that is, a file pointer must be defined before opening it. (3) The function call format described later will directly write out the data type of the formal parameter and the data type of the function return value. For example: The function of open file above, return a file pointer, in the form of the number of two, are character variables (string array or string pointer). The software no longer specifically describes the invocation format of the function. Now let's look at how to use the Open file function. The first formal parameter in the fopen () function represents a file name, which can include both the path and the file name. such as: "B:test. DAT "" C://tc//test. DAT "Assume that the path is written as" c:/tc/test. DAT "is wrong, pay special attention to this point. The second form parameter indicates the type of open file. The provisions regarding the types of documents are shown in the table below. Table file operation type ━━━━━━━━━━━━━━━━━━━━━━━━━━━━ character meaning ──────────────────────────── "R" Open text file Just read "W" Create text file just write "A" supplement, assuming the file does not existCreate a "r+" to open a text file read/write "w+" Create a text file read/write "A +" open or create a file supplement "B" binary file (can be combined with each of the above) "T" this file (default) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━ assume that you want to open a Ccdos subfolder, The file name is a binary file called Clib, which can be written as: fopen ("C://ccdos//clib", "RB"); Assuming a successful open file, the fopen () function returns the file pointer, otherwise a NULL pointer (NULL) is returned. This allows you to infer whether the file opened successfully. 2. The fclose () function fclose () function is used to close a file opened by the fopen () function, which is called in the following format:intFcloseFILE*stream); The function returns an integer number. Returns 0 if the file is closed successfully, otherwise a non-0 value is returned. The ability to infer whether a file is closed successfully based on the return value of the function. Example: #iclude <stdio.h> main () {FILE*FP; /* Define a file pointer */intI Fp=fopen ("CLIB", "RB"); /* Open the file with the current folder named Clib Read Only */if(fp==null)/* Infer whether the file is open successfully */puts ("File open Error");/* Prompt open unsuccessful/i=fclose (FP); /* Close the Open file */if(i==0)/* Infer if the file is closed successfully */printf ("o,k"); /* Prompt to close success */ElsePuts ("File close error");/* Prompt Close unsuccessful */} second, functions related to file operations This section refers to the file read and write functions are referred to the sequential read and write, that is, after reading and writing a message, the pointer itself actively add 1. The following describes the write operation function and the read operation function respectively. 1. The sequential write function of the file fprintf (), fputs (), and FPUTC () function Functions fprintf (), fputs (), and FPUTC () are the sequential write operations functions of the file, which are called in a format such as the following:intfprintf (FILE*stream,Char*format, <variable-list>);intFputsChar*string,FILE*steam);intFPUTC (intChFILE*steam); The return values of the above three functions are integer. The return value of the fprintf () function is the number of characters (in bytes) that are actually written to the file. Assuming a write error, a negative number is returned, and the Fputs () function returns 0 o'clock indicating that the string pointer was written to the file in a successful operation and returned to non-0 o'clock, indicating that the write operation failed. The FPUTC () function returns a value that writes to the file, at which time the write operation succeeds, or EOF (which ends with a value of 1 and is defined in stdio.h) indicates a write error. The fprintf () function is formatted in the same way as the printf () function, and the only difference is that the fprintf () function is written to the file. and printf () is output to the screen. The following is an example of a Test.dat file that executes post-natal. Example: #include <stdio.h> main () {Char*s= "That ' s good news"); /* Define a string pointer and initialize */inti=617; /* Define integer variables and initialize */FILE*FP; /* Define the file pointer */FP=FOPNE ("Test.dat", "w"); /* Create a text file just write */fputs ("Your score of Toeflis", FP);/* Write a string of characters to the file */FPUTC (': ', FP); /* Write a colon to the file you built: */fprintf (FP, "%d/n", I); /* Write an integer number to the file created */fprintf (FP, "%s", s); /* Write a string to the built file */fclose (FP); /* Close file */} Use the DOS type command to display the contents of TEST.DAT as seen below: Screen display Your score of the TOEFL is:617 that's good news 2. The sequential read operation functions of the file fscanf (), fgets (), and fgetc () function Functions fscanf (), fgets (), and fgetc () are sequential read operation functions of the file, whose invocation format is as follows:intfscanfFILE*stream,Char*format, <address-list>);CharFgetsChar*string,intNFILE*steam);intFGETC (FILE*steam); The fscanf () function is used in a way similar to the scanf () function, just because it reads information from a file. The return value of the fscanf () function is EOF (that is,-1), indicating a read error, otherwise the read data succeeds. The fgets () function reads up to n-1 characters from the file (n is used to specify the number of characters), and puts them in a string-pointing character, and then, after reading it, voluntarily adds a null character to the string, and the read successfully returns a string pointer, failing to return a null pointer. The FGETC () function returns a character in the current position of the file, which returns EOF when the error is read. The following program reads the Test.dat file produced by example 11 and displays the read results on the screen. Example #include <stdio.h> main () {Char*s, m[20];intIFILE*FP; Fp=fopen ("Test.dat", "R"); /* Open Text file read Only */fgets (s, FP); /* Read 23 characters from a file */printf ("%s", s); /* Output the Read String */fscanf (FP, "%d", &i); /* Read integer number */printf ("%d", I); /* Outputs the number of read integers */Putchar (FGETC (FP)); /* read one character at the same time output */fgets (M, p, FP); /* Read 16 characters */puts (m); /* Output the Read String */fclose (FP); /* Close File */Getch (); /* Wait for either key */} to perform a screen display: Your score of the TOEFL is:617 that's good news assumes that the above example fscanf (FP, "%d", &i) is changed to FSCANF (f P, "%s", m), and then change the output statement to printf ("%s", m), then the same result can be obtained. This shows the Turbo C2. In 0, if a text file is only read, both the character and the number are treated as ASCII values. It is also important to note that the FSCANF () function reads the white space character, the self-active end, in the use of special attention. 3. Random Read and write files sometimes users want to directly read the file inside wearer information, if the file in the order of reading and writing must start from the beginning of the file until the requested file location re-read, this is obviously inconvenient. The Turbo C2.0 provides a random read and write function for a set of files that is able to position the file position pointer directly to read and write where required. The random read-write function for the file is as follows:intFseek (FILE*stream,LongOffsetintFromwhere);intFreadvoid*buf,intSizeintCountFILE*stream);intFwritevoid*buf,intSizeintCountFILE*stream);LongFtellFILE*stream); The function of the fseek () function is to set the position pointer of the file to the position of the offset byte starting at Fromwhere, where Fromwhere is one of the following macro definitions: The position of the file position pointer start calculation location Fromwhere ━━━━━━━━━━━━━━━━━━━━━━━━━━━ Symbolic constant numeric meaning ───────────────────────────seek_set 0 from the beginning of the file Seek_cur 1 from the current position of the file pointer Seek_end 2 from the end of the file ━━━━━━━━━━━━━━━━━━━━━━━━━━━offset refers to the file location refers to The number of bytes skipped by the pin from the specified start position (the position indicated by Fromwhere). It is a long integer quantity to support files larger than 64K bytes. The fseek () function is typically used to manipulate binary files. When the fseek () function returns 0 o'clock indicating that the operation was successful, returning a non-0 indicates a failure. The following program reads the 8th byte from a binary file test_b.dat. Example: #include <stdio.h> main () {FILE*FP;if((Fp=fopen ("Test_b.dat", "RB")) ==null) {printf ("Can ' t Open file"); Exit (1); } fseek (FP, 8.1, Seek_set); FGETC (FP); Fclose (FP); The Fread () function reads count fields from the file, each field length is a size byte, and stores them in the buffer referred to by the BUF pointer. The fwrite () function is to write the Count field of size bytes to the buffer in which the BUF pointer refers to the file pointed to by the stream. As the number of read and write sections increases, the file position indicator also increases, how many bytes are read, and how many bytes the file position indicator skips. The read-Write completion function returns the number of fields that are read and written. The Ftell () function returns the current value of the file position indicator, which is the number of bytes from the beginning of the file header, the number returned is a long integer, and the error occurs when 1 is returned. The following program writes a floating-point array to the file Test_b.dat in binary mode. Example: #include <stdio.h> main () {floatf[6]={3.2,-4.34, 25.04, 0.1, 50.56, 80.5}; /* Define a floating-point group and Initialize */intIFILE*FP; Fp=fopen ("Test_b.dat", "WB"); /* Create a binary file just write */fwrite (F,sizeof(float), 6, FP);/* Writes 6 floating-point numbers to a file */fclose (FP); /* Close file */} The following sample reads 100 integers from the Test_b.dat file and puts them in the DAT array. Example: #include <stdio.h> main () {FILE*FP;intDAT[100]; Fp=fopen ("Test_b.dat", "RB");/* Open a binary file just read */if(Fread (DAT,sizeof(int), 100, FP)/* Infer whether or not to read the number of!=100 */{if(feof (FP)) printf ("End of File"); /* Less than 100 number of files end */Elseprintf ("Read error"); /* Reading Error */fclose (FP); /* Close file */} NOTE: When using standard file functions to read and write files, the read-write content is first put into the buffer, that is, the write function only operates on the output buffer, and the read function only operates on the input buffer. For example, writing to a file, the content will be placed in the output buffer, until the output buffer is full or use the fclose () function to close the file, the contents of the buffer will be written into the file. Without the fclose () function, no content is written to or written to the file. There is a function to flush the buffer, that is, fflush (), whose invocation format is:intFflushFILE*stream); This function actually writes the contents of the output buffer to the file and clears the contents of the input buffer. 4. The feof () and rewind () functions are called in the following format:intFeofFILE*stream);intRewindFILE*stream); The feof () function detects if the file position indicator has reached the end of the file, or returns a value other than 0 if it returns 0. This function is particularly useful for binary file operations, because in binary files, the end of file symbol EOF is also a valid binary number, simply checking the value of the read-in character to infer whether the file is finished is not possible. In that case, you might end up with a file that doesn't end, so you have to have the feof () function. The following statement is a method that is often used to infer whether a file is ending. while(!feof (FP)) fgetc (FP); The while is a looping statement, which is described in the following. The rewind () function is used to move the file position indicator to the beginning of the file, return 0 on success, or return a value other than 0. 1.2.2 Non-standard file functions such functions are first used in Unix operating systems, the ANSI standard is not defined, but sometimes often used, the DOS 3.0 or more version number supports these functions. Their header file is io.h. One, open and close the file 1. The open () function opens the file with the following format:intOpenChar*filename,intAccess); This function means that a file named filename is opened as required by access, and the return value is a file descriptive narrative, in which access has two parts: the basic mode and the modifier, which are connected in a "(" or ") manner. Modifiers can have multiple, but the basic pattern can only have one. Access is provided in table 3-2. Table 3-2 Access rules ━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Basic mode meaning modifier meaning ────────────────────────────o_rdonly read only O_append file pointer to end o_wronly only write O_creat file does not exist when creating file, properties O_rdwr read/write by basic mode property O_tr UNC If the file exists, its length is reduced to 0, the property is unchanged o_binary open a binary file O_text Open a text file the ━━━━━━━━━━━━━━━━━━━━━━━━━━━━open () function opens successfully, and the return value is the value (non-negative) of the descriptive narrative of the file, otherwise returns-1. 2. The close () function's close () function closes the file opened by the open () function with the following format:intCloseinthandle); This function closes the file describing the narrative word handle connected to the file. Second, read and write function 1. The read () function of the read () function is called in the format:intReadintHandlevoid*buf,intcount); The read () function reads the count bytes into the buffer referred to by BUF from handle (the file description Word), the return value is the actual number of bytes read, and a return of 1 indicates an error. Returning 0 indicates the end of the file. 2. The write () function of the write () function is called in the following format:intWriteintHandlevoid*buf,intcount); The write () function writes count bytes from BUF to the buffer that is attached to the handle, and the return value is the number of bytes actually written. Three, the random positioning function 1. The call format for the Lseek () function Lseek () function is:intLseek (intHandleLongOffsetintFromwhere); This function locates the file position pointer that is connected to the handle and uses the same function as the fseek () function. 2. The tell () function call format is:LongTellinthandle); The function returns the current position pointer to the file attached to the handle, and the function and use method is the same as Ftell ().
fopen () function