// direct.c -- fwrite()和fread()用法演示 #include <stdio.h> #include <stdlib.h> #define SIZE 20 int main(void){ int count, array1[SIZE], array2[SIZE]; FILE *fp; // 给array1[]中的元素赋值 for(count = 0; count < SIZE; count++) array1[count] = 2 * count; //打开二进制模式文件 if((fp = fopen("direct.txt", "wb")) == NULL){ fprintf(stderr, "Error opening file."); exit(1); } //把array[]1保存至文件中 if(fwrite(array1, sizeof(int), SIZE, fp) != SIZE){ fprintf(stderr, "Error writing to file."); exit(1); } fclose(fp); //以二进制模式打开相同的文件读取数据 if((fp = fopen("direct.txt", "rb")) == NULL){ fprintf(stderr, "Error opening file."); exit(1); } //读取array2[]中的数据 if(fread(array2, sizeof(int), SIZE, fp) != SIZE){ fprintf(stderr, "Error reading file."); exit(1); } fclose(fp); //显示两个数组中的内容 for(count = 0; count < SIZE; count++) printf("%d\t%d\n", array1[count], array2[count]); return 0; }