C语言文件输入输出问题

按要求写前n个数据到文本文件lb8204.txt,然后从该文件读数据并显示。写入的数据是1到1000中是7的倍数或者是数字中含7的数(如:37,71,72等)。图中80是键盘输入的,每个数占4个宽度,每10个数换一行。注:只允许在/******start******/和/******end******/之间添加代码。代码:#include <stdio.h>#include <stdlib.h>void save(int n);void out(void);int main(void){ int n; printf("Input n:"); scanf("%d", &n); save(n); out(); return 0;}void save(int n){ /******start******/ /******end******/}void out(void){ char str[48]; FILE *fp; fp = fopen("lb8204.txt", "r"); if (fp == NULL) { exit(0); } printf("Output:\n"); while (!feof(fp)) { fgets(str, 44, fp); printf("%s", str); } printf("\n"); fclose(fp);}

void save(int n){
/******start******/
    int i,j;
    FILE *fp;
    if((fp=fopen("lb8204.txt","w"))==NULL){
        printf("Open the file failure...\n");
        exit(0);
    }
    for(j=0,i=7;i<1000 && j<n;i++)
        if(i%7==0 || i%10==7 || i/10%10==7 || i/100==7){
            fprintf(fp,"%4d",i);
            if(++j%10==0)
                fputc('\n',fp);
        }
    fclose(fp);
    /******end******/
}

另:此题有错误——

while(!feof(fp)){
    fgets(str, 44, fp);
    printf("%s", str);
}

得改成

while(fgets(str, 44, fp),!feof(fp)){
    printf("%s", str);
}

或改成

fgets(str, 44, fp);
while(!feof(fp)){
    printf("%s", str);
    fgets(str, 44, fp);
}

否则,最后会重复读出一行或乱码。正规书上的题出此显错,有点贻笑大方……

温馨提示:答案为网友推荐,仅供参考
相似回答