# 1B-13 ###### tags: `一上程設` ### eg1 ``` #include <stdio.h> #include <stdlib.h> #include <time.h> int main() { FILE *fp; int prn, i; fp = fopen("txtfile.txt", "w"); if(fp == NULL) { printf("File open error.\n"); exit(EXIT_FAILURE); } srand(time(NULL)); printf("Filling the file with pseudorandom numbers ... \n\n"); for(i = 0; i < 10; i++) { prn = rand() % 20; fprintf(fp, "%d ", prn); } printf("Retrieved data from txtfile.txt ...\n"); rewind(fp); fp = fopen("txtfile.txt", "r"); for(i = 0; i < 10; i++) { fscanf(fp, "%d", &prn); printf("%d ", prn); } printf("\n\n"); fclose(fp); return 0; } ``` ### eg1.1 ``` #include <stdio.h> #include <stdlib.h> #include <time.h> int main() { FILE *fp; int i; double prn; fp = fopen("txtfile.txt", "w"); if(fp == NULL) { printf("File open error.\n"); exit(EXIT_FAILURE); } srand(time(NULL)); rand(); printf("Filling the file with pseudorandom numbers ... \n\n"); for(i = 0; i < 10; i++) { prn = 1.0 / (RAND_MAX + 1.0) * rand(); fprintf(fp, "%f ", prn); } printf("Retrieved data from txtfile.txt ...\n"); rewind(fp); fp = fopen("txtfile.txt", "r"); for(i = 0; i < 10; i++) { fscanf(fp, "%lf", &prn); printf("%f ", prn); } printf("\n\n"); fclose(fp); return 0; } ``` ### eg2 ``` #include <stdio.h> #include <stdlib.h> #include <time.h> int main() { FILE *fp; int prn, i; fp = fopen("binFile.dat", "w+b"); if(fp == NULL) { printf("File open error.\n"); exit(EXIT_FAILURE); } srand(time(NULL)); printf("Filling the file with pseudorandom numbers ... \n\n"); for(i = 0; i < 10; i++) { prn = rand() % 20; fwrite(&prn, sizeof(int), 1,fp); } printf("Retrieved data from binFile.dat ...\n"); rewind(fp); for(i = 0; i < 10; i++) { fread(&prn, sizeof(int), 1, fp); printf("%d ", prn); } printf("\n\n"); fclose(fp); return 0; } ``` ### Practice 2. ``` #include <stdio.h> #include <stdlib.h> int main() { FILE *fp; int prn, i; int a[5] = {0, 1, 2, 3, 4}, b[5]; fp = fopen("binFile.dat", "wb"); if(fp == NULL) { printf("File open error.\n"); exit(EXIT_FAILURE); } fwrite(a, sizeof(int), 5,fp); printf("Retrieved data from binFile.dat ...\n"); rewind(fp); fp = fopen("binFile.dat", "rb"); fread(b, sizeof(int), 5, fp); for(i = 0; i < 5; i++) printf("%d ", b[i]); printf("\n\n"); fclose(fp); return 0; } ``` ### EXTRA ``` #include <stdio.h> #include <stdlib.h> int main() { FILE *fp; int prn, i, q; int a[5] = {0, 1, 2, 3, 4}, b[5]; fp = fopen("binFile.dat", "w+b"); if(fp == NULL) { printf("File open error.\n"); exit(EXIT_FAILURE); } fwrite(a, sizeof(int), 5,fp); rewind(fp); fread(b, sizeof(int), 5, fp); rewind(fp); printf("顯示第幾個元素:"); scanf("%d", &q); if(fseek(fp, q * sizeof(int), SEEK_SET) == 0) { printf("the index you enter is %d", b[q]); } printf("\n\n"); fclose(fp); return 0; } ```