Format read and write functions fscanf and fprintf
The fscanf function and the fprintf function are similar to the functions of the scanf and printf functions used earlier, and are both formatted read and write functions. The difference between the two is that the read and write objects of the fscanf function and the fprintf function are not keyboards and monitors, but disk files. The calling 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 problem of Example 10.6 can also be completed using fscanf and fprintf functions. 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 with Example 10.6, the fscanf and fprintf functions in this program can only read and write one structural array element at a time, so loop statements are used to read and write all array elements. Also note that the pointer variables pp and qq change their values, since the loop changes their values, they are reassigned to the first address of the array on lines 25 and 32 of the program respectively.
Random read and write files
The reading and writing methods of files introduced above are all sequential reading and writing, that is, reading and writing files can only start from scratch and read and write each data in sequence. However, in practical problems, it is often required to read and write only a specified part of the file. In order to solve this problem, you can move the position pointer inside the file to the location where it needs to be read and written, and then read and write. This kind of reading and writing is called random reading and writing. The key to achieving random read and write is to move the position pointer as required, which is called file positioning. There are two main functions for moving the internal position pointer of a file, namely the rewind function and the fseek function.
The rewind function has been used many times before, and its call form is: rewind (file pointer); its function is to move the position pointer inside the file to the beginning of the file. The following main introduction
fseek function.
The fseek function is used to move the internal position pointer of the file. Its call form is: fseek (file pointer, displacement amount, starting point); where: "file pointer" points to the moved file. "Displacement" represents the number of bytes moved, and the displacement is required to be long-type data so that there will be no errors when the file length is greater than 64KB. When using a constant to represent the displacement, the suffix "L" is required. "Start point" indicates where to start calculating the displacement. There are three specified starting points: file head, current position and file end.
The representation method is shown in Table 10.2.
Start point, symbol, number
──────────────────────────
File Header SEEK—SET0
Current location SEEK—CUR1
At the end of the file SEEK—END 2
For example:
fseek(fp,100L,0); Its meaning is to move the position pointer to 100 bytes from the first of the file. It should also be noted that the fseek function is generally used in binary files. In text files, there are often errors in the calculation position. After the random read and write of a file is moved, you can use any of the read and write functions introduced above to read and write. Since it is generally to read and write a data block, fread and fwrite functions are commonly used. The following use case questions illustrate the random reading and writing of files.
[Example 10.8] Read the data of the second student in the student file 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);
}
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 file stu_list has been established by the program in Example 10.6. This program uses a random read method to read out the data of the second student. The boy is defined in the program as a stu type variable, and qq is a pointer to the boy. Open the file by reading a binary file, and move the file position pointer on line 22 of the program. The i value is 1, which means that starting from the file header, moving the length of a stu type, and then reading the data is the data of the second student.
File detection function
There are the following commonly used file detection functions in C language.
1. File end detection function feof function call format: feof (file pointer);
Function: Determine whether the file is at the end of the file. If the file ends, the return value is 1, otherwise it is 0.
2. Read and write file error detection function ferror function call format: ferror (file pointer);
Function: Check whether a file is errored when reading and writing with various input and output functions. If the return value of ferror is 0, it means there is no error, otherwise it means there is an error.
3. File error flag and file end flag set 0 function clearerr function call format: clearerr (file pointer);
Function: This function is used to clear the error flag and the end of the file flag to make them 0 values.
C library file
The C system provides a rich system file, called library files. The library files of C are divided into two categories. One is a file with the extension ".h", called header files. We have used it many times in the previous inclusion command. The ".h" file contains information such as constant definition, type definition, macro definition, function prototype, and various compilation selection settings. Another type is the function library, which includes the object code of various functions for users to call in the program. Usually when calling a library function in a program, the ".h" file where the function prototype is located is included before the call is called.
All library functions are given in the appendix.
Explain memory management functions (allocation, release, etc.).
Definition assert debug macro.
Description: Each function that calls the IBM-PC ROM BIOS subroutine.
Description of the functions that call the DOS console I/O subroutine.
Contains name information about character classification and conversion (such as isalpha and toascii, etc.).
Contains structures, macro definitions and functions related to directories and paths.
Define and describe some constants and functions called by MSDOS and 8086.
mnemonic that defines the error code.
Defines symbolic constants when connected to the open library subroutine.
Contains some parameters and functions related to floating point operations.
Explain the various functions related to the graphics functions, the constant definition of the graphics error code, the various color values for different drivers, and some special structures used by the functions.
Contains the structure and description of low-level I/O subroutines.
Contains information such as each environment parameter, compilation time limit, and number range.
Explain the mathematical operation function, and set the HUGE VAL macro, explaining the special structure used by the matherr and matherr subr programs.
Explain some memory operation functions (most of them are also explained in ).
Explain the structure description of each function of process management, spawn… and EXEC… functions.
Define the jmp buf type used in the longjmp and setjmp functions, and explain these two functions.
Define the parameters of the file sharing function.
Define SIG[ZZ(Z] [ZZ)]IGN and SIG[ZZ(Z] [ZZ)]DFL constants, explaining the two functions rajse and signal.
Define macros that read function parameter table. (such as vprintf, vscarf function).
Define some public data types and macros.
Define the types and macros of the standards and extensions defined by Kernighan and Ritchie in Unix System V. Also define standard I/O predefined streams: stdin, stdout and stderr to illustrate the I/O stream subroutine.
Explain some commonly used subroutines: conversion subroutines, search/sorting subroutines, etc.
Explain some string operations and memory operation functions.
SYS\ Define some symbolic constants used when opening and creating files.
SYS\ Describe the ftime function and timeb structure.
SYS\ Define the type time[ZZ(Z] [ZZ)]t.
Define the structure of the time conversion subroutine asctime, localtime and gmtime, the types used by ctime, difftime, gmtime, localtime and stime, and provide prototypes of these functions.
Define some important constants, including some constants that depend on the sum of the machine hardware, which is specified for compatibility with Unix System V, including the range of floating point and double precision values.
Previous page12Read the full text