C examples for File:File Operation
The following program writes and then reads back a double, an int, and a long to and from a disk file.
It uses sizeof to determine the length of each data type.
#include <stdio.h> #include <stdlib.h> int main(void) { FILE *fp;//from w w w. j av a2s . c o m double d = 12.23; int i = 101; long l = 123023L; if ((fp = fopen("test", "wb+")) == NULL) { printf("Cannot open file.\n"); exit(1); } fwrite(&d, sizeof(double), 1, fp); fwrite(&i, sizeof(int), 1, fp); fwrite(&l, sizeof(long), 1, fp); rewind(fp); fread(&d, sizeof(double), 1, fp); fread(&i, sizeof(int), 1, fp); fread(&l, sizeof(long), 1, fp); printf("%f %d %ld", d, i, 1); fclose(fp); return 0; }