Fread and fwrite Functions
Fread and fwrite Functions
1. Function Functions
Used to read and write a data block.
2. General call form
Fread (buffer, size, Count, FP );
Fwrite (buffer, size, Count, FP );
3. Description
(1) buffer: A pointer. For fread, It is the storage address for reading data. For fwrite, It is the address of the data to be output.
(2) size: the number of bytes to read and write;
(3) count: the number of data items of size bytes to be read and written;
(4) FP: file pointer.
4. Example
Example 1 input the data of four students from the keyboard and then store the data to a disk file.
(1) algorithm analysis;
(2) Procedure see: li13-3.c
Example 2 reads the relevant data from the file generated in Example 1 and then outputs the data on the screen.
(1) algorithm analysis;
(2) Procedure see: li13-4.c
※Fwrite, fread, and fopen read/write struct. ※
Fwrite and fread are used to read and write files. The summary is in the code comments. Note that binary mode is used for reading and writing, and problems may occur in text mode.
# I nclude "iostream"
# I nclude "iomanip"
Using namespace STD;
Typedef struct tagtest
{
Char name [40];
Int size;
Int array [200];
} Test, * Ptest;
Void output (test * s)
{
Cout <"struct name is:" <s-> name <Endl;
Cout <"struct size is:" <s-> size <Endl;
Cout <"struct datas:" <Endl;
For (INT I = 0; I <200 ;)
{
Cout <SETW (8) <s-> array [I];
If (++ I % 8 = 0)
Cout <Endl;
}
Cout <Endl;
}
Int main (INT argc, char * argv [])
{
Test mytest;
Strcpy (mytest. Name, "A single write and read file example ");
Mytest. size = sizeof (test );
For (INT I = 0; I <200; I ++)
Mytest. array [I] = I;
// Display the data before the file is written. Check whether the data is consistent with the data read after the file is written.
Output (& mytest );
// Write an object
File * FP;
// Open the file, "W +", opens an empty file for both reading and writing.
// If the given file exists, its contents are destroyed
// Read and write data in binary mode, instead of text mode. When opening a file, the line feed is "/n" in binary mode ",
// In binary mode, the line feed is processed as two bytes.
If (FP = fopen ("D: // mytest. Out", "WB +") = NULL)
{
Cout <"file cannot be created" <Endl;
Return-1;
}
Fwrite (const void *) & mytest, sizeof (mytest), 1, FP );
Float otherdata [500];
// Write another data after the struct.
For (I = 0; I <500; I ++)
Otherdata [I] = I * 2;
Fwrite (const void *) otherdata, sizeof (otherdata), 1, FP );
Fclose (FP );
// Read the file.
Cout <*********** * ******* "<Endl;
File * fr;
Fr = fopen ("D: // mytest. Out", "RB + ");
If (Fr = NULL)
{
Cout <"no file found! "<Endl;
Return-1;
}
Test myread;
Fread (void *) & myread, sizeof (myread), 1, fr );
Float temp [500]; // used to store read data.
Fread (void *) temp, sizeof (temp), 1, fr );
Fclose (FR );
// The following shows whether the read is correct.
Cout <myread. Name <Endl;
Cout <myread. Size <Endl;
Output (& myread );
Cout <"******************** this is the data behind the result body ********* * ************* "<Endl;
For (I = 0; I <500 ;)
{
Cout <SETW (8) <temp [I];
If (++ I % 8 = 0)
Cout <Endl;
}
Cout <Endl;
Return 0;
}
Data Block read/write functions fread and fwrite
The C language also provides read/write functions for the entire data block. It can be used to read and write a group of data, such as an array element and a value of a structure variable. The call Method for reading data block functions is fread (buffer, size, Count, FP). The call Method for writing data block functions is fwrite (buffer, size, count, FP); buffer is a pointer. In the fread function, it indicates the first address to store the input data. In the fwrite function, it indicates the first address of the output data. Size indicates the number of bytes of the data block. Count indicates the number of data blocks to read and write. FP indicates the file pointer.
For example:
Fread (FA, FP); it means that four bytes (a real number) are read each time from the file indicated by FP and sent to the real array FA for five consecutive reads, read 5 real numbers into fa.
[Example 10.6] input two student data from the keyboard, write them into a file, and read the data of the two students on the screen.
# Include <stdio. h>
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 % 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 ADDR/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 );
}
In this example, the program defines a structure Stu, indicating two arrays Boya and boyb, and two structure pointer variables PP and QQ. PP points to Boya, QQ points to boyb. Line 2 of the program opens the binary file "stu_list" in read/write mode, enters two student data, writes it to the file, and moves the internal position pointer of the file to the beginning of the file, after reading two pieces of student data, it is displayed on the screen.
Formatting read/write functions fscanf and fprintf
The fscanf function and fprintf function are similar to the functions of the scanf and printf functions used earlier. They are both formatted read/write functions. The difference between the fscanf function and fprintf function is that the Read and Write objects are not keyboard and display, but disk files. The call formats of these two functions are: fscanf (File pointer, Format String, input table column); fprintf (File pointer, Format String, output table column); for example:
Fscanf (FP, "% d % s", & I, S );
Fprintf (FP, "% d % C", J, CH );
The fscanf and fprintf functions can also be used to solve the problem in the case of 10.6. Shows the modified program in example 10.7.
[Example: 10.7]
# Include <stdio. h>
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 % s", PP-> name, & PP-> num, & PP-> Age, PP-> ADDR );
Pp = Boya;
For (I = 0; I <2; I ++, pp ++)
Fprintf (FP, "% S % d % s/n", PP-> name, PP-> num, PP-> Age, PP->
ADDR );
Rewind (FP );
For (I = 0; I <2; I ++, QQ ++)
Fscanf (FP, "% S % 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 with example 10.6, in this program, the fscanf and fprintf functions can read and write only one structural array element at a time. Therefore, they use loop statements to read and write all array elements. Note that the pointer variable PP, QQ, has changed their values cyclically, so they are re-assigned the first address of the array in line 25 and 32 of the program.
Random file read/write
The read and write methods for files are sequential read and write, that is, the read and write files can only start from the beginning, read and write data sequentially. However, in practice, it is often required that a specified part of the read-only file be written. To solve this problem, the position pointer inside the file is moved to the location where the file needs to be read and written before reading and writing. This read and writing is called random read and write. The key to achieving random read/write is to move the location pointer as required, which is called file location. There are two main functions used to locate and move the internal position pointer of a file, namely the rewind function and the fseek function.
The rewind function has been used multiple times before and is called in the form of rewind (File pointer). Its function is to move the position pointer inside the file to the beginning of the file. The following describes
Fseek function.
The fseek function is used to move the internal position pointer of a file. The call form is fseek (File pointer, displacement, starting point). The "file Pointer" points to the object to be moved. "Displacement" indicates the number of bytes to move. The displacement is long data, so that no error occurs when the file length is greater than 64 KB. When a constant is used to represent the displacement, the suffix "L" is required ". The "Starting Point" indicates where to start the calculation of the displacement. There are three defined starting points: the first part of the file, the current position, and the end of the file.
The representation is shown in Table 10.2.
Starting point represents a symbolic number.
── ─
First seek-set 0
Current location seek-cur 1
Seek-end 2 at the end of the file
For example:
Fseek (FP, 100l, 0); it means to move the position pointer to the first 100 bytes away from the file. It must be noted that the fseek function is generally used for binary files. In a text file, the location of the calculation is often incorrect because the conversion is required. After moving the pointer, you can use any of the read/write functions described earlier. Generally, fread and fwrite functions are commonly used to read and write data blocks. The following example describes the random read/write operations of a file.
[Example 10.8] read the data of the second student in the student file Stu list.
# Include <stdio. h>
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 );
}
Rewind (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 stu_list file has been created by the program in example 10.6. This program reads the data of the second student by random reading. The program defines boy as a stu type variable, and QQ as a pointer to boy. Open the file by reading the binary file, and the program moves the file location pointer in line with 22nd. The value of I is 1, which indicates that starting from the file header, the length of an Stu type is moved, and then the data read is the data of the second student.
File Detection Functions
The following file detection functions are commonly used in C language.
1. File end detection function feof function call format: feof (File pointer );
Function: determines whether the object is at the end of the object. If the object ends, the return value is 1. Otherwise, the return value is 0.
Ii. file read/write error detection function ferror function call format: ferror (File pointer );
Function: checks whether an error occurs when a file is read or written using various input/output functions. If the return value of ferror is 0, it indicates no error; otherwise, it indicates an error.
3. Set the file error mark and file end sign to 0. clearerr function call format: clearerr (File pointer );
Function: This function is used to clear the error mark and end mark of a file so that they are 0 values.
C library file
C system provides a wide range of system files, called library files. C library files are divided into two types, one is the extension ". H "file, called the header file, has been used many times in the preceding include command. The ". H" file contains constant definition, type definition, macro definition, function prototype, and various compilation and selection settings. Another type is the function library, which includes the target code of various functions for users to call in the program. When a library function is called in a program, the ". H" file of the function prototype must be included before the function is called.
All database functions are provided in the appendix.
Alloc. h indicates memory management functions (such as allocation and release ).
Assert. h defines assert debugging macros.
BiOS. h describes the various functions that call the IBM-PC rom bios subroutine.
Conio. h indicates that each function of the I/O subprogram of the DOS console is called.
Ctype. h contains the name class information about character classification and conversion (such as isalpha and toascii ).
Dir. h contains the Directory and path structures, macro definitions, and functions.
Dos. h defines and describes some constants and functions called by msdos and 8086.
Erron. h defines the entrustment of the error code.
Fcntl. h defines the symbolic constant used to connect to the Open Library subroutine.
Float. h contains some parameters and functions related to floating point operations.
Graphics. h describes various functions related to graphic functions, constant definitions of graphic error codes, various color values of different drivers, and some special structures used by functions.
Io. h contains the structure and description of low-level I/O subprograms.
Limit. h contains environment parameters, compilation time limits, number ranges, and other information.
Math. h describes the mathematical operation functions, and defines the huge Val macro, which describes the special structures used by matherr and matherr subprograms.
Mem. h indicates some memory operation functions (most of them are also described in string. h ).
Process. h describes the various functions of process management, spawn... And exec... Function structure description.
Setjmp. h defines the JMP Buf types used by longjmp and setjmp functions.
Share. h defines the parameters of the file sharing function.
Signal. h defines the SIG [ZZ (Z] [zz)] ign and SIG [ZZ (Z] [zz)] DFL constants, indicating the rajse and signal functions.
Stdarg. h defines the macro of the read function parameter table. (Such as vprintf and vscscarf functions ).
Stddef. h defines some common data types and macros.
Stdio. h defines the standard and extended types and macros defined by kernighan and Ritchie in UNIX System V. Standard I/O predefined streams: stdin, stdout, and stderr are also defined to describe the I/O Stream subprograms.
Stdlib. h describes some common subprograms, such as conversion subprograms and search/sort subprograms.
String. h describes some string operations and memory operation functions.
Sys/STAT. h defines some symbolic constants used to open and create files.
Sys/types. h describes the ftime function and timeb structure.
Sys/time. h defines the time type time [ZZ (Z] [zz)] T.
Time. h defines the structure of the time conversion subprograms asctime, localtime, and gmtime, the types used by ctime, difftime, gmtime, localtime, and stime, and provides prototype of these functions.
Value. h defines some important constants, including those dependent on machine hardware and which are described for compatibility with UNIX System V, including floating point and double precision value ranges.