The fscanf and fprintf functions are similar to those of scanf and printf, both of which are 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 (FP, "% d % s", & num, STR );
Fprintf (FP, "% d % C", num, CH); // FP is the file pointer
Example:
Input five student data on the keyboard, write a file, and read the data of the five students on the screen.
# Include <stdio. h> struct stud {char name [10]; int num;} SW [5], Sr [5], * PW, * PR; // define an int main () {file * FP; int I; If (FP = fopen ("D: \ abc.txt ", "WB +") = NULL) // open the file {printf ("cannot open a file! ");} PW = Sw; // the pointer PW points to the array SW Pr = Sr; // the pointer PR points to the array Sr printf (" input data \ n "); printf ("name num \ n"); for (I = 0; I <5; I ++) scanf ("% S % d", SW [I]. name, & SW [I]. num); for (I = 0; I <5; I ++, PW ++) // read data into the file. Note that the point of PW changes to fprintf (FP, "% S % d \ n", PW-> name, PW-> num); rewind (FP); // move the internal pointer of the file to the file header for (I = 0; I <5; I ++, PR ++) fscanf (FP, "% S % d \ n", pr-> name, & pr-> num ); // read the information from the file into the struct printf ("\ nname num \ n"); for (I = 0; I <5; I ++) printf ("% S % 5d \ n", Sr [I]. name, Sr [I]. num); // read the information from the struct fclose (FP); // close the file return 0 ;}