File Operation 1, operation 1
Simple File Operations
// Input the records of the two students into the txt file and display them on the screen # include <stdio. h> # include <stdlib. h> # define N 2 typedef struct stu {char Class [20]; int age; char name [9];} stu; // The type that needs to be customized (typedef ), stu can define the object int main () {int I, n; char Class [20]; int age; char name [9]; FILE * fp; printf ("Write student information to file: \ n"); fp = fopen ("E: \ c \ stu.txt", "w "); // write the specified file for (I = 0; I <N; I ++) {printf ("student class:"); scanf ("% s ", & Class); printf ("student age:"); scanf ("% d", & age); print F ("Student name:"); scanf ("% s", & name); fprintf (fp, "% s % 6d % 10 s", Class, age, name); // write the student information to the file in fputc ('\ n', fp ); // if no message is written, '\ n' can be replaced with' \ R'} fclose (fp). // close the printf file ("read student information from the file: \ n "); fp = fopen (" E: \ c \ stu.txt "," r "); // read the specified file for (I = 0; I <N; I ++) {fscanf (fp, "% s % 6d % 20 s", & Class, & age, & name); printf ("student Class: % s, student age: % d, Student name: % s \ n ", Class, age, name);} fclose (fp ); printf ("APPEND student information to the file: \ n"); fp = fopen ("E: \ c \ stu.txt", "wb "); Printf (" APPEND count: "); scanf (" % d ", & n); stu * s = (stu *) malloc (sizeof (stu) * n); // dynamically opens the struct array for (I = 0; I <n; I ++) {printf ("student class :"); scanf ("% s", & s [I]. class); printf ("student age:"); scanf ("% d", & s [I]. age); printf ("Student name:"); scanf ("% s", & s [I]. name);} if (fwrite (& s, sizeof (stu), n, fp )! = N) // if the operation is successful, the number of data blocks actually written to the file is returned {printf ("the file cannot write data! \ N "); exit (1) ;}fclose (fp); printf (" trace student information from the file: \ n "); fp = fopen (" E: \ c \ stu.txt "," rb "); if (fread (& s, sizeof (stu), n, fp )! = N) // if the operation is successful, the number of data blocks actually read from the file is returned {printf ("the file cannot read data! \ N "); exit (1) ;}for (I = 0; I <n; I ++) {printf (" Student Class: % s, student age: % d, Student name: % s \ n ", s [I]. class, s [I]. age, s [I]. name) ;}fclose (fp); return 0 ;}