#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> int main(void) { static int a[100], a2[100]; FILE * fp1; FILE * fp2; FILE * fp3; int num, i; int index = 0; float fnum = 1.0f / 7.0f, fnum2 = 0.0; if ((fp1 = fopen("C:\\1.txt", "r")) == NULL) { puts("File 1.txt cannot be opened !"); exit(1); } if ((fp2 = fopen("C:\\2.txt", "w+")) == NULL) { puts("File 2.txt cannot be opened !"); exit(1); } if ((fp3 = fopen("C:\\3.bin", "wb+")) == NULL) { puts("File 3.bin cannot be opened !"); exit(1); } while (fscanf(fp1, "%d", &num) == 1) { a[index++] = num; fprintf(fp2, "%d ", num); } /* ungetc(' ', fp2); */ putc('\n', fp2); fputs("Hello file1 !", fp2); printf("The offset of fp1 is: "); printf("%d\n", ftell(fp1)); printf("The offset of fp2 is: "); printf("%d\n", ftell(fp2)); fseek(fp1, 0L, SEEK_SET); fseek(fp2, 0L, SEEK_SET); /* for (i = 0; i < index; i++) { printf("%d ", a[i]); } putchar('\n'); */ if (fwrite(a, index * sizeof(int), 1, fp3) != 1) { puts("fwrite error !"); exit(1); } fseek(fp3, 0L, SEEK_SET); /* 还原fp3 */ if (fread(a2, sizeof(int), index, fp3) != index) { puts("fread error !"); exit(1); } puts("The integers read from fp3 is: "); for (i = 0; i < index; i++) { printf("%d ", a2[i]); } putchar('\n'); fseek(fp3, 0L, SEEK_END); if (fwrite(&fnum, sizeof(float), 1, fp3) != 1) { puts("The float number cannot be writen to the file !"); exit(1); } fseek(fp3, -1L * sizeof(float), SEEK_END); if (fread(&fnum2, sizeof(float), 1, fp3) != 1) { puts("The float number in the file is failed to read !"); exit(1); } printf("%.7f\n", fnum2); fclose(fp1); fclose(fp2); fclose(fp3); return 0; }