// 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; }