Mega Code Archive

 
Categories / C / Code Snippets
 

Save and read string into a file

#include <stdio.h> #include <stdlib.h> double d[10] = { 1.3, 2.7, 1.4, 1.9, 0.7, 1.4, 4.4, 2.0, 1.1, 3.5 }; int main(void) { int j; FILE *filep; if((filep = fopen("myfile.txt", "wb"))==NULL) { printf("Cannot open file.\n"); exit(1); } for( j = 0; j < 10; j++) if(fwrite(&d[j], sizeof( double ), 1, filep) != 1) { printf("Write error.\n"); exit(1); } fclose(filep); if((filep = fopen("myfile.txt", "rb"))==NULL) { printf("Cannot open file.\n"); exit(1); } /* clear the array */ for(j = 0; j < 10; j++) d[j] = -1.0; for(j = 0; j < 10; j++) if(fread(&d[j], sizeof(double), 1, filep) != 1) { printf("Read error.\n"); exit(1); } fclose(filep); /* display the array */ for(j = 0; j < 10; j++) printf("%f ", d[j]); return 0; }