【C语言程序设计第四版】练习12-6
实数取整写入文件
#include <stdio.h> #include <stdlib.h> #define MAXN 300 int main(void){ int i,j; FILE *fp, *fp1; double nums[MAXN]; if ((fp=fopen("f1.txt", "r")) == NULL) { printf("File open errpr!\n"); exit(0); } if ((fp1=fopen("f2.txt", "w")) == NULL) { printf("File open errpr!\n"); exit(0); } i = 0; while (!feof(fp)) { fscanf(fp, "%lf", &nums[i]); i++; } for (j=0; j<i-1; j++) { fprintf(fp1, "%.0f ", nums[j]); } if ((fclose(fp))) { printf("Can not close the file!\n"); exit(0); } if ((fclose(fp1))) { printf("Can not close the file!\n"); exit(0); } return 0; }
改进版本,不需要定义数组
#include <stdio.h> #include <stdlib.h> #define MAXN 300 int main(void){ int i,j; FILE *fp, *fp1; double nums; if ((fp=fopen("f1.txt", "r")) == NULL) { printf("File open errpr!\n"); exit(0); } if ((fp1=fopen("f2.txt", "w")) == NULL) { printf("File open errpr!\n"); exit(0); } fscanf(fp, "%lf", &nums); while (!feof(fp)) { fprintf(fp1, "%.0f ", nums); fscanf(fp, "%lf", &nums); } if ((fclose(fp))) { printf("Can not close the file!\n"); exit(0); } if ((fclose(fp1))) { printf("Can not close the file!\n"); exit(0); } return 0; }