Fopen () function

Source: Internet
Author: User
Tags fread integer numbers rewind
1.2 file input and output functions
The input and output of logical devices, such as keyboards, monitors, printers, and disk drives, can be completed through file management. The most commonly used disk files are used for programming. Therefore, this section mainly focuses on disk files and describes in detail the file operation functions provided by Turbo c2.0, of course, these file operation functions are also suitable for non-disk files.
In addition, Turbo c2.0 provides two types of file functions. One class is called a standard file function or a buffer file function, which is defined by the ANSI standard function, and the other class is called a non-standard file function, which is also called a non-buffer file function. This type of function was first used in UNIX operating systems, but is now available in MS-DOS3.0 and later versions. The following is an introduction.
1.2.1 standard file functions
Standard file functions include functions such as opening, closing, reading, and writing a file. Unlike basic and FORTRAN, there are sequential files and random files, which should be determined in different ways when opened. Turbo c2.0 does not distinguish between these two types of files, but provides two sets of functions: sequential read/write and random read/write.
1. Open and Close a file
Any file must be opened and closed before and after use. This is because the operating system limits the number of files opened at the same time. In the DOS operating system, in device. sys defines the number of files that can be opened at the same time (defined by files = N ). Where N is the number of files that can be opened at the same time, generally n <= 20. Therefore, you must open the file before using the file to access the information. You must disable it after use. Otherwise, unexpected errors may occur. Turbo c2.0 provides functions to open and close files.
1. fopen () function
The fopen function is used to open a file. The call format is:
File* Fopen ( Char* Filename, * type );
Before introducing this function, you must first understand the following knowledge of functions.
(1) stream and file)
Stream and file are different in Turbo c2.0. Turbo c2.0 provides an abstraction between the programmer and the accessed device, called "stream ", the actual device is called a file. A stream is a logical device with the same behavior. Therefore, the function used to write disk files can also be used to write printer files. There are two types of stream in Turbo c2.0: Text Stream and binary stream ). For a disk, it is a text file and binary file. In order to make it easy for readers to understand the language of Turbo c2.0, this software makes no special distinction between streaming and files.
(2) file pointer
In fact, file is a new data type. It is a collection of basic data types of Turbo c2.0 and is called a structure pointer. The concept of structure will be detailed in section 4. Here, we only need to understand file as a data structure that includes information about file management, that is, you must first define a file pointer when opening a file.
(3) The function call format described later will directly write the Data Type of the form parameter and the Data Type of the function return value. For example, the function that opens the file above returns a file pointer. There are two formal parameters, both of which are character variables (string array or string pointer ). The software will not detail the function call format.
Now let's take a look at the usage of the file function.
The first form parameter in the fopen () function represents the file name, which can contain two parts: path and file name. For example:
"B: test. dat"
"C:/TC/test. dat"
Note that writing the path "C:/TC/test. dat" is incorrect.
The second form parameter indicates the type of the file to open. For more information about file types, see the following table.
Table File Operation Type
When there are too many threads, there are too many threads, too many threads.
Character meaning
── ─
"R" Open Text File Read-Only
"W" Create a text file and write only
"A" addition. If the file does not exist, create
"R +" open a text file to read/write
"W +" Create a text file read/write
"A +" open or create a file supplement
"B" binary file (can be used with each of the above items)
"T" file (default)
When there are too many threads, there are too many threads, too many threads.
To open a binary file named cLib in the ccdos subdirectory, you can write it as follows:
Fopen ("C:/ccdos/cLib", "rb ");
If a file is successfully opened, the fopen () function returns the file pointer; otherwise, null is returned ). This allows you to determine whether the file is successfully opened.
2. fclose () function
The fclose () function is used to close a file opened by the fopen () function. The Calling format is:
IntFclose ( File* Stream );
This function returns an integer. If the object is successfully closed, 0 is returned; otherwise, a non-zero value is returned. You can determine whether the file is successfully closed based on the return value of the function.
Example 10:
# Iclude <stdio. h>
Main ()
File* FP;/* define a file pointer */
Fp = fopen ("cLib", "rb");/* open the file named cLib in the current directory */
If(FP = NULL)/* determine whether the file is successfully opened */
Puts ("file open error");/* Indicates opening failed */
I = fclose (FP);/* close the opened file */
If(I = 0)/* determine whether the file is successfully closed */
Printf ("O, K");/* message indicating successful shutdown */
Puts ("file close error");/* The system prompts "failed to close */
Ii. functions related to file operations
The file read/write functions mentioned in this section refer to sequential read/write. After reading and writing a piece of information, the pointer automatically adds 1. The following describes the write and read operation functions respectively.
1. sequential file write function
Fprintf (), fputs (), and fputc () Functions
The fprintf (), fputs (), and fputc () functions are sequential write operation functions of files. The Calling format is as follows:
IntFprintf ( File* Stream, Char* Format, <variable-List> );
IntFputs ( Char* String, File* Steam );
IntFputc ( IntCh, File* Steam );
The return values of the preceding three functions are integer values. The Return Value of the fprintf () function is the number of characters (in bytes) in the actually written file ). If a write error occurs, a negative number is returned. When the fputs () function returns 0, it indicates that the string indicated by the string pointer is successfully written into the file. If the return value is not 0, the write operation fails. The fputc () function returns the value of a character written to the file. At this time, the write operation is successful. Otherwise, the returned value of EOF (the end of the file is-1, at stdio. h) indicates a write operation error.
The formatting rules in the fprintf () function are the same as those in the printf () function. The difference is that the fprintf () function writes data to the file. While printf () is output to the screen.
The following is an example of a file named test. dat after running.
Example 11:
# Include <stdio. h>
Main ()
Char* S = "that's good news");/* define the 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 and write only */
Fputs ("your score of toeflis", FP);/* write a string of characters to the created file */
Fputc (':', FP);/* write the colon :*/
Fprintf (FP, "% d/N", I);/* write an integer to the created file */
Fprintf (FP, "% s", S);/* write a string to the created file */
Fclose (FP);/* close the file */
Use the dos type command to display the content of test. dat as follows:
Screen Display
Your score of TOEFL is: 617
That's good news
2. Sequential read operation functions of Files
Fscanf (), fgets (), and fgetc () Functions
The fscanf (), fgets (), and fgetc () functions are sequential read operation functions of files. The Calling format is as follows:
IntFscanf ( File* Stream, Char* Format, <address-List> );
CharFgets ( Char* String, IntN, File* Steam );
IntFgetc ( File* Steam );
The usage of the fscanf () function is similar to that of the scanf () function, but it reads information from the file. The Return Value of the fscanf () function is EOF (-1), indicating that the data is read incorrectly. Otherwise, the data is read successfully. The fgets () function reads up to n-1 characters from the file (N is used to specify the number of characters) and places them into the string to which the string points, after reading, an empty character is automatically added to the end of the string. If the read succeeds, the string pointer is returned. If the read succeeds, a null pointer is returned. The fgetc () function returns a character at the current position of the file, and an EOF is returned when a read error occurs.
The following program reads the test. dat file generated in example 11 and displays the read result on the screen.
Example 12
# Include <stdio. h>
Main ()
Char* S, M [20];
File* FP;
Fp = fopen ("test. dat", "R");/* Open the text file read-only */
Fgets (S, 24, FP);/* read 23 characters from the file */
Printf ("% s", S);/* output the read string */
Fscanf (FP, "% d", & I);/* read Integer Number */
Printf ("% d", I);/* output the number of read integers */
Putchar (fgetc (FP);/* read one character and output at the same time */
Fgets (M, 17, FP);/* read 16 characters */
Puts (m);/* output the read string */
Fclose (FP);/* close the file */
Getch ();/* one-click wait */
Screen Display after running:
Your score of TOEFL is: 617
That's good news
If you change fscanf (FP, "% d", & I) in the preceding example to fscanf (FP, "% s", m ), then, change the output statement to printf ("% s", m) to get the same result. It can be seen that in Turbo C2. 0, as long as a text file is read, both characters and numbers are processed according to their ASCII values. In addition, the fscanf () function automatically stops when it reads a blank space.
3. Random file read/write
Sometimes users want to directly read the information somewhere in the middle of the file. It is obviously inconvenient to read the information from the file header to the requested file location in sequence. Turbo c2.0 provides a set of random read/write functions for files, that is, the file location pointer can be located in the required read/write location for direct read/write.
The random read/write functions of files are as follows:
IntFseek ( File* Stream, LongOffset, IntFromwhere );
IntFread ( Void* Buf, IntSize, IntCount, File* Stream );
IntFwrite ( Void* Buf, IntSize, IntCount, File* Stream );
LongFtell ( File* Stream );
The fseek () function is used to set the file position pointer to the offset byte starting from fromwhere. fromwhere is one of the following macro definitions:
The starting position of the file location pointer. fromwhere is the starting position.
Numerical meaning of symbolic constants ── ─
Seek_set 0 starts with a file
Seek_cur 1 from the current position of the file pointer
Seek_end 2: starting from the end of the file, there will be too many other such problems.
Offset refers to the number of bytes that the file position pointer skips from the specified starting position (indicated by fromwhere. It is a long integer to support files larger than 64 KB. The fseek () function is generally used to operate binary files.
If the fseek () function returns 0, the operation is successful. If the return value is not 0, the operation fails.
The following program reads 8th bytes from the binary file test_ B .dat.
Example 13:
# 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 a file. Each field is in size and is stored in the buffer indicated by the Buf pointer.
The fwrite () function writes the Count fields of the buffer indicated by the Buf pointer in size to the file pointed by stream.
As the number of Read and Write segments increases, the file position indicator increases. The number of bytes to read and the number of bytes to read will also be skipped. The number of fields read and written by the read/write function is returned.
The ftell () function returns the current value of the file location indicator, which is the number of bytes counted from the file header. The number returned is a long integer. If-1 is returned, an error occurs.
The following program writes a floating point number group to the file test_ B .dat in binary mode.
Example 14:
# 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 it */
File* FP;
Fp = fopen ("test_ B .dat", "WB");/* Create a binary file and write only */
Fwrite (F, Sizeof( Float), 6, FP);/* write 6 floating point numbers to the file */
Fclose (FP);/* close the file */
The following example reads 100 integer numbers from the test_ B .dat file and puts them in the DAT array.
Example 15:
# Include <stdio. h>
Main ()
File* FP;
IntDat [1, 100];
Fp = fopen ("test_ B .dat", "rb");/* open a binary file read-only */
If(Fread (dat, Sizeof( Int), 100, FP )! = 100)
/* Determine whether 100 entries have been read */
If(Feof (FP ))
Printf ("End of file");/* ends with less than 100 files */
Printf ("read error");/* reading error */
Fclose (FP);/* close the file */
When a standard file function is used to read and write a file, the read and 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, to write content to a file, the written content will first be placed in the output buffer, until the output buffer is full or the fclose () function is used to close the file, the buffer content will be written into the file. If there is no fclose () function, it will not save the written content to the file or the written content is incomplete. There is a function to refresh the buffer zone, that is, fflush (). Its call format is:
IntFflush ( File* Stream );
This function writes the content of the output buffer to the file and clears the content of the input buffer.
4. feof () and rewind () Functions
The call formats of these two functions are:
IntFeof ( File* Stream );
IntRewind ( File* Stream );
The feof () function checks whether the file position indicator has reached the end of the file. If yes, a non-0 value is returned; otherwise, 0 is returned. This function is particularly useful for binary file operations, because in binary files, the end mark EOF the file is also a legal binary number, it is not feasible to simply check the value of the characters to determine whether the file ends. In that case, the file may not end and be considered as the end. Therefore, the feof () function must exist.
The following statement is a commonly used method to determine whether a file is terminated.
While(! Feof (FP ))
Fgetc (FP );
While is a loop statement, which will be described below.
The rewind () function is used to move the Object Location indicator to the start point of the object. If the object is successful, 0 is returned. Otherwise, a non-0 value is returned.
1.2.2 Non-standard file functions
These functions were first used in UNIX operating systems and are not defined in the ANSI standard, but are often used. Dos 3.0 and later versions support these functions. Their header files are Io. h.
1. Open and Close a file
1. open () function
The open () function is used to open a file. The call format is as follows:
IntOpen ( Char* Filename, IntAccess );
This function indicates that the file named filename is opened according to access requirements, and the return value is the file description. Access has two parts: Basic Mode and modifier, the two are connected in the "(" or ") mode. There can be multiple modifiers, but there can be only one modifier in the basic mode. The access rules are shown in Table 3-2.
Table 3-2 access regulations: definitions of the basic schema modifier ── ─ ── o_rdonly read-only o_append file pointer pointing to the end of o_wronly write only o_creat file does not exist when the file is created,
Attribute read/write o_trunc according to basic mode attribute o_rdwr if the file exists, set its length
Scale down to 0 and keep attributes unchanged
O_binary open a binary file
O_text open a text file.
The open () function is successfully opened. The returned value is the value of the file description (non-negative value). Otherwise,-1 is returned.
2. Close () function
The function close () is used to close files opened by the open () function. The Calling format is:
IntClose ( IntHandle );
This function disables handle-connected files.
Ii. read/write Functions
1. Read () function
The Calling format of the read () function is:
IntRead ( IntHandle, Void* Buf, IntCount );
The read () function reads count bytes from the files connected by the handle (File description) and puts them in the buffer zone referred to by the Buf. the return value is the actual number of bytes read. The return value-1 indicates an error. 0 indicates the end of the file.
2. Write () function
The Calling format of the write () function is:
IntWrite ( IntHandle, Void* Buf, IntCount );
The write () function writes count bytes from the buffer to which the Buf points to the file connected to the handle. The returned value is the actual number of bytes written.
Iii. Random locating Functions
1. lseek () function
The call format of the lseek () function is:
IntLseek ( IntHandle, LongOffset, IntFromwhere );
This function locates the file location pointer connected to the handle. Its functions and usage are the same as those of the fseek () function.
2. Tell () function
The call format of the tell () function is:
LongTell ( IntHandle );
This function returns the current position pointer of the file connected to handle. The function and usage are the same as those of ftell.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.