Mega Code Archive

 
Categories / C / Code Snippets
 

Save and write different type of value into file

#include <stdio.h> #include <stdlib.h> int main(void) { FILE *filep; int j; /* open file for output */ if((filep = fopen("myfile.txt", "wb"))==NULL) { printf("Cannot open file.\n"); exit(1); } j = 10; if(fwrite(&j, sizeof(int), 1, filep) != 1) { printf("Write error occurred.\n"); exit(1); } fclose(filep); /* open file for input */ if((filep = fopen("myfile.txt", "rb"))==NULL) { printf("Cannot open file.\n"); exit(1); } if(fread(&j, sizeof j, 1, filep) != 1) { printf("Read error occurred.\n"); exit(1); } printf("j is %d",j); fclose(filep); return 0; }