回复 楼主 ZMX900507
简单描述下我的思路:文件1存放数字,文件2存放频率,文件3存放满足条件的字符。不需要数组,每次从文件1和文件2各读取一行,取乘积判断,满足条件就存放到文件3。
[qq]949654600[/qq]
#include <stdio.h> #include <stdlib.h> #include <string.h> #define q 0.03 void haLen(FILE *fp, int *len) { int a, b; char *fmt = "%d\t%d"; while(!feof(fp)) { fscanf(fp, fmt, &a, &b); *len++ = b - a + 1; } } int clacLine(FILE *fp, int len) { char c[80]; int cur = 0; while(!feof(fp)) { fgets(c, 80, fp); if((c[len] == '\n' || c[len] == '\0') && c[0] != '\n' && c[0] != '\0') { cur++; c[len] = '\0'; } } return cur; } void readFileH(FILE *fp, int cur, int len, char (*p)[len + 1]) { int i; rewind(fp); for(i = 0; i < cur; i++) { fgets(*(p + i), len + 1, fp); fgetc(fp); } } void readFileF(FILE *fp, int cur, double *p) { int i; for(i = 0; i < cur; i++) { fscanf(fp, "%lf", p + i); fgetc(fp); } } void newfile(FILE *fpNew, int len, int cur, char (*pHa)[len + 1], double *pF, char *strNum) { for(int i = 0; i < cur ; i++) { if((atoi(*(pHa + i)) * *(pF + i)) > q) { fwrite(pHa + i, sizeof(char), strlen(*(pHa + i)), fpNew); sprintf(strNum, "%lf", *(pF + i)); fwrite(strNum, sizeof(char), strlen(strNum), fpNew); fprintf(fpNew, "\n"); } } } int main(void) { int len[4], cur; char strNum[8]; FILE *fpQiZhi = fopen("fenkuailianjieqizhi.txt", "r"); FILE *fpHa1 = fopen("ha1.txt", "r"); FILE *fpHa2 = fopen("ha2.txt", "r"); FILE *fpHa3 = fopen("ha3.txt", "r"); FILE *fpHa4 = fopen("ha4.txt", "r"); FILE *fpF1 = fopen("f1.txt", "r"); FILE *fpF2 = fopen("f1.txt", "r"); FILE *fpF3 = fopen("f1.txt", "r"); FILE *fpF4 = fopen("f1.txt", "r"); FILE *fpNew = fopen("new.txt", "wb"); haLen(fpQiZhi, len); /*--------------------------------------------*/ cur = clacLine(fpHa1, len[0]); char (*pHa)[len[0] + 1] = malloc(cur * (len[0] + 1) * sizeof(char)); double *pF = malloc(cur * sizeof(double)); readFileH(fpHa1, cur, len[0], pHa); readFileF(fpF1, cur, pF); newfile(fpNew, len[0], cur, pHa, pF, strNum); /*--------------------------------------------*/ cur = clacLine(fpHa2, len[1]); realloc(pHa, cur * (len[1] + 1) * sizeof(char)); realloc(pF, cur * sizeof(double)); readFileH(fpHa2, cur, len[1], pHa); readFileF(fpF2, cur, pF); newfile(fpNew, len[1], cur, pHa, pF, strNum); /*--------------------------------------------*/ cur = clacLine(fpHa3, len[2]); realloc(pHa, cur * (len[2] + 1) * sizeof(char)); realloc(pF, cur * sizeof(double)); readFileH(fpHa3, cur, len[2], pHa); readFileF(fpF3, cur, pF); newfile(fpNew, len[2], cur, pHa, pF, strNum); /*--------------------------------------------*/ cur = clacLine(fpHa4, len[3]); realloc(pHa, cur * (len[3] + 1) * sizeof(char)); realloc(pF, cur * sizeof(double)); readFileH(fpHa3, cur, len[3], pHa); readFileF(fpF3, cur, pF); newfile(fpNew, len[3], cur, pHa, pF, strNum); /*--------------------------------------------*/ free(pF); free(pHa); fclose(fpQiZhi); fclose(fpHa1); fclose(fpHa2); fclose(fpHa3); fclose(fpHa4); fclose(fpF1); fclose(fpF2); fclose(fpF3); fclose(fpF4); fclose(fpNew); return 0; }