The fscanf () and fprintf () functions, similar to the scanf () and printf () features used earlier, are formatted read-write functions, the difference being that the read-write objects of fscanf () and fprintf () are not keyboard and monitor, but disk files.
The prototypes for these two functions are:
int fscanf (FILE *fp, char * format, ...);
int fprintf (FILE *fp, char * format, ...);
FP is file pointer, format control string, ... Represents a list of parameters. Compared to scanf () and printf (), they have only one more FP parameter. For example:
FILE *FP;
int I, J;
Char *str, ch;
FSCANF (FP, "%d%s", &i, str);
fprintf (FP, "%d%c", J, ch);
fprintf () returns the number of characters that were successfully written, and negative numbers are returned if they fail. FSCANF () returns the number of parameters in the parameter list that were successfully assigned.
The example uses the FSCANF and fprintf functions to read and write student information.
#include <stdio.h> #define N 2 struct stu{char name[10];
int num;
int age;
Float score;
} Boya[n], boyb[n], *pa, *PB;
int main () {FILE *fp;
int i;
Pa=boya;
Pb=boyb;
if ((Fp=fopen ("D:\\demo.txt", "wt+")) = = NULL) {printf ("Cannot open file, press any key exit!");
Getch ();
Exit (1);
}//Read data from the keyboard, save to Boya printf ("Input data:\n");
For (i=0 i<n; i++,pa++) {scanf ("%s%d%d%f", Pa->name, &pa->num, &pa->age, &pa->score);
PA = Boya; Writes data from Boya to file for (i=0 i<n; i++,pa++) {fprintf (FP, "%s%d%f\n", Pa->name, Pa->num, Pa->age, Pa->
; score);
//Reset file Pointer rewind (FP); Reads data from a file and saves it to Boyb for (i=0 i<n; i++,pb++) {fscanf (FP, "%s%d%d%f\n", Pb->name, &pb->num, &pb->
; age, &pb->score);
} Pb=boyb; Output data from Boyb to display for (i=0 i<n; i++,pb++) {printf ("%s%d%d%f\n", Pb->name, Pb->num, Pb->age, PB->SC
ore);
Fclose (FP);
return 0; }
Run Result:
Input Data:
Tom 2 15 90.5↙
Hua 1 14 99↙
Tom 2 15 90.500000
Hua 1 14 99.000000
Open D:\\demo.txt, found that the contents of the file can be read, the format is very clear. Using fprintf () and fscanf () functions to read and write configuration files, log files will be very convenient, not only the program can identify, users can understand, you can manually modify.
If the FP is set to stdin, then the FSCANF () function will read the data from the keyboard, the same as the scanf, and the fprintf () function will output the content to the monitor, the same as printf. For example:
#include <stdio.h>
int main () {
int A, b, sum;
fprintf (stdout, "Input two numbers:");
FSCANF (stdin, "%d%d", &a, &b);
sum = a + b;
fprintf (stdout, "sum=%d\n", sum);
return 0;
}
Run Result:
Input two numbers:10 20↙
Sum=3036.html
The above is the C language format read and write files of data collation, follow-up continue to supplement the relevant information, thank you for your support of this site!