Input and Output Functions of file C

Source: Internet
Author: User
Tags fread integer numbers rewind
File Input and Output Functions
Keyboard, display, printer, disk drive, and other logical devices.
Component Management Method. In programming, the most commonly used disk files are used. Therefore, this section mainly uses
Disk Files are the main types of file operation functions provided by Turbo c2.0. Of course, these operations on files
Functions are also suitable for non-disk files.
In addition, Turbo c2.0 provides two types of file functions. A class is also called as a standard file function.
Buffer-type file functions, which are defined by ANSI standards. Another type is called non-standard file functions, also known as non-standard file functions.
Buffer file functions. This type of function was first used in UNIX operating systems, but now the MS-DOS3.0 and later versions
This operating system can also be used. 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,
The Fortran language can be divided into sequential files and random files. It should be determined in different ways when it is opened.
Turbo c2.0 does not distinguish these two types of files, but provides two sets of functions: sequential read/write functions and random read functions.
Write a function.
1. Open and Close a file
Any file must be opened and closed before and after use.
The number of files simultaneously opened is limited in the operating system. In the DOS operating system
. SYS defines the number of files that can be opened at the same time (defined by files = n ). N indicates a file that can be opened at the same time.
Number of pieces, 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
And the function that closes the file.

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 is the programmer and accessed
A layer of abstraction is provided between the slave node and the slave node, which is called a "stream", and the actual device is called a file.
A stream is a logical device with the same behavior. Therefore, the same function is used to write disk files.
It can be used to write data to a printer. There are two types of stream in Turbo C2.0: text Stream (text Stream
Stream) and binary (binary stream ). For a disk, it is a text file and binary file. Ben
In order to make it easier for readers to understand the language of Turbo C2.0, the 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,
It is called a structure pointer. The concept of the structure will be detailed in section 4. Here you only need to understand the FILE
Is a data structure that includes information about file management.
Pointer.
(3) The function call format described later will directly write the data type and function return value of the form parameter.
. For example, the function used to open the file above returns a file pointer. The format parameters include
Both are character variables (string array or string pointer ). The software no longer calls the function.
Statement.
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, a null pointer is returned.
(Null ). 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:
Int fclose (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 */
Int I;
Fp = fopen ("CLIB", "rb");/* open the file named CLIB in the current directory */
If (FP = NULL)/* determines whether the file is successfully opened */
Puts ("file open error");/* Indicates opening failed */
I = fclose (FP);/* close the opened file */
If (I = 0)/* determines whether the file is successfully closed */
Printf ("O, K");/* message indicating successful shutdown */
Else
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 message, the pointer automatically
Add 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.
Format:
Int fprintf (FILE * stream, char * format, <variable-list> );
Int fputs (char * string, FILE * steam );
Int fputc (int ch, FILE * steam );
The return values of the preceding three functions are integer values. The Return Value of the fprintf () function is the actual written text.
The number of characters (in bytes ). If a write error occurs, a negative number is returned. When the fputs () function returns 0
Indicates that the string indicated by the string pointer is successfully written into the file. If the return value is not 0, it indicates the write operation.
Failed. The fputc () function returns the value of a character written to the file. The write operation is successful. Otherwise
Return EOF (the end value of the file is-1, defined in stdio. h) indicates a write operation error.
The formatting rules in the fprintf () function are the same as those in the printf () function, except that
The fprintf () function writes data to a 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 */
Int I = 617;/* define Integer Variables and initialize */
FILE * fp;/* define 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.
As follows:
Int fscanf (FILE * stream, char * format, <address-list> );
Char fgets (char * string, int n, FILE * steam );
Int fgetc (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. Fgets () function
Number of reads up to n-1 characters from the file (n is used to specify the number of characters), and puts them into the string pointing
After reading the string, an empty character is automatically added to the string before the end. If the string is read successfully, the string pointer is returned,
A null pointer is returned for failure. The fgetc () function returns a character from the current position of the file.
Back to EOF.
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];
Int I;
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) to fscanf (FP, "% s", m) in the preceding example
The output Statement of is changed to printf ("% s", m), and the same result can be obtained. It can be seen that Turbo C2. 0
As long as it is a text file, both characters and numbers are processed according to their ASCII values. In addition
Note that the fscanf () function automatically ends when it reads a blank space.

3. Random file read/write
Sometimes you want to directly read the information somewhere in the middle of the file.
It is obviously inconvenient to start from the header until the requested file location is read again. Turbo C2.0 provides a set of files
A random read/write function can be used to locate the file position pointer and directly read and write the file at the desired read/write location.
The random read/write functions of files are as follows:
Int fseek (FILE * stream, long offset, int fromwhere );
Int fread (void * buf, int size, int count, FILE * stream );
Int fwrite (void * buf, int size, int count, FILE * stream );
Long ftell (FILE * stream );
The fseek () function is used to set the position pointer of a file to the offset starting from fromwhere.
In bytes, fromwhere is one of the following macro definitions:
File Location pointer start computing location fromwhere
When there are too many threads, there are too many threads, too many threads.
Symbol constant numerical meaning
── ─
SEEK_SET 0 starts with a file
SEEK_CUR 1 from the current position of the file pointer
SEEK_END 2 from the end of the file
When there are too many threads, there are too many threads, too many threads.
Offset indicates that the file position pointer is skipped from the specified start position (indicated by fromwhere ).
Number of nodes. It is a long integer to support files larger than 64 KB. The fseek () function is generally used
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 length of size, and
They are stored in the buffer referred to by the buf pointer.
The fwrite () function refers to the buffer referred to by the buf pointer, which is a count word with a length of size.
To the file pointed to by stream.
As the number of Read and Write nodes increases, the file location indicator also increases, the number of bytes read, the file bit
The number of bytes skipped by the indicator. 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 starts from the file header.
The number of bytes. The number returned is a long integer. If-1 is returned, an error is returned.
The following program writes a floating point number group to the file test_ B .dat in binary mode.
Example 14:
# Include <stdio. h>
Main ()
{
Float f [6] = {3.2,-4.34, 25.04, 0.1, 50.56, 80.5 };
/* Define a floating point group and initialize it */
Int I;
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;
Int dat [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 */
Else
Printf ("Read error");/* reading error */
Fclose (fp);/* close the file */
}
Note:
When a standard file function is used to read and write a file, the read and write content is first put into the buffer zone,
That is, write functions only operate on the output buffer, and read functions only operate on the input buffer. For example
File write content, the written content will first be placed in the output buffer until the output buffer is full or
When the fclose () function is used to close a file, the buffer content is written to the file. If no fclose ()
Function. There is a pair of Buffer
The Calling format of the refreshed function, namely fflush (), is:
Int fflush (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:
Int feof (FILE * stream );
Int rewind (FILE * stream );
The feof () function checks whether the file location indicator has reached the end of the file. If yes, a non-0
Value. Otherwise, 0 is returned. This function is particularly useful for binary file operations, because in binary files
The end mark (EOF) is also a valid binary number. It only checks the value of the characters to judge the text.
It is impossible to end the parts. If that is the case, the file may not end and is considered as the end.
The feof () function is required.
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 file location indicator to the start point of the file. If the file is successful, 0 is returned. No
Then, a non-0 value is returned.

1.2.2 Non-standard file functions
This type of function is first used in UNIX operating systems, and the ANSI standard is undefined, but it is 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:
Int open (char * filename, int access );
This function indicates to open the file named filename as required by access. The returned value is the file description,
Access has two parts: the basic mode and modifier. The two are connected in the "(" or ") mode. Repair
There can be multiple modifiers, but only one of the basic modes can be. The access rules are shown in Table 3-2.
Table 3-2 access rules
When there are too many threads, there are too many threads, too many threads.
Meaning modifier of Basic Mode
── ─
O_RDONLY read-only O_APPEND file pointer pointing to the end
O_WRONLY creates a file when only the O_CREAT file does not exist,
Attribute by basic mode attribute
O_RDWR read/write O_TRUNC 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
When there are too many threads, there are too many threads, too many threads.
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:
Int close (INT handle );
This function disables handle-connected files.

Ii. read/write Functions
1. Read () function
The Calling format of the read () function is:
Int read (INT handle, void * Buf, int count );
The read () function reads count bytes from the files connected by the handle (File description) and places them in the Buf
In the buffer referred to, the returned value is the actual number of bytes read, and "-1" is returned, indicating an error. Returns 0 to indicate the file.
End.

2. Write () function
The Calling format of the write () function is:
Int write (INT handle, void * Buf, int count );
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 number of bytes actually written.

Iii. Random locating Functions
1. lseek () function
The call format of the lseek () function is:
Int lseek (INT handle, long offset, int fromwhere );
This function locates the file location pointer connected to handle. Its function and usage are similar to that of fseek ().
The number is the same.

2. tell () function
The call format of the tell () function is:
Long tell (int handle );
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: info-contact@alibabacloud.com 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.