// struct to file #include <stdlib.h> struct person int id; char lname[20]; { outfile = fopen ( 'person.dat' , 'w' ); { exit (1); struct person input1 = {1, 'rohan' , 'sharma' }; struct person input2 = {2, 'mahendra' , 'dhoni' }; // write struct to file fwrite (&input1, sizeof ( struct person), 1, outfile); fwrite (&input2, sizeof ( struct person), 1, outfile); if ( fwrite != 0) printf ( 'contents to file written successfully !' ); printf ( 'error writing file !' ); // close file } |
// struct from a file #include <stdlib.h> // struct person with 3 fields { char fname[20]; }; // Driver program { struct person input; // Open person.dat for reading if (infile NULL) fprintf (stderr, 'Error opening file' ); } // read file contents till end of file while ( fread (&input, sizeof ( struct person), 1, infile)) input.fname, input.lname); // close file } |