Mega Code Archive

 
Categories / C / Code Snippets
 

Use fprintf and fscanf to save and read file

#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { FILE *filep; double ld; int d; char str[80]; if(argc!=2) { printf("Specify file name.\n"); exit(1); } /* open file for output */ if((filep = fopen(argv[1], "w"))==NULL) { printf("Cannot open file.\n"); exit(1); } fprintf(filep, "%f %d %s", 345.342, 908, "Clementine"); fclose(filep); /* open file for input */ if((filep = fopen(argv[1], "r"))==NULL) { printf("Cannot open file.\n"); exit(1); } fscanf(filep, "%lf%d%s", &ld, &d, str); printf("%f %d %s", ld, d, str); fclose(filep); return 0; }