首页 > 解决方案 > 文件的读写

问题描述

我是 c 的新手,我想检查一下我是否了解文件处理的功能是如何工作的,这是我的代码。我面临的问题是每个 x 中 fx 的评估成功存储在文件 pointinterpol.dat 上,但是当我想读取以将其内容存储在两个数组上并打印它们时,我得到了 x,y 数组的所有元素零。我不知道出了什么问题?

int main(void)
{
    int i = 0;
    float xe;
    float x[8], y[8];
    float fx = 1 / (1 + 25 * xe * xe);
    FILE* fptr = NULL;
    FILE* fread;
    fptr = fopen("pointinterpol.dat", "w");
    xe = -1;
    while (i++ < 8)
    {
        fprintf(fptr, "%.3f  %.3f\n", xe, 1 / (1 + 25 * xe * xe));
        xe += 0.25;
    }
    i = 0;
    fread = fopen("pointinterpol.dat", "r");
    while (fscanf(fread, "%f %f", &x[i], &y[i]) == 2)
    {
        i++;
    }
    i = 0;
    while (i < 8)
    {
        printf("\nx[%d] = %.2f *** y[%d] = %.2f\n", i, x[i], i, y[i]);
        i++;
    }
    flcose(fptr);
    fclose(fread);
    return 0;
}

标签: arrayscfile-handling

解决方案


正如评论中所指出的,您需要fclose()在完成将数据写入文件后调用。我fclose()在第一个 while 循环之后添加,我能够看到预期的输出:

#include <stdio.h>

int main(void) {
    int i=0;
    float xe;
    float x[8],y[8];
    float fx = 1 / (1 + 25*xe*xe);
    FILE *fptr = NULL;
    FILE *fread;
    fptr = fopen("pointinterpol.dat","w"); // -> File Opened for Writing
    xe = -1;
    while( i++ < 8 ) {
        fprintf(fptr,"%.3f  %.3f\n",xe,1/(1+25*xe*xe));
        xe += 0.25;
    }
    fclose(fptr); // -> Writing finished, close stream
    i=0;
    fread = fopen("pointinterpol.dat","r"); // -> File opened for reading
    while(fscanf(fread,"%f %f",&x[i],&y[i]) == 2) {
        i++;
    }
    i=0;
    while( i < 8 ) {
        printf("\nx[%d] = %.2f *** y[%d] = %.2f\n",i,x[i],i,y[i]);
        i++;
    }
    fclose(fread); // -> Reading finished, close stream after use
    return 0;
}

当我运行它时,我得到这个输出:


x[0] = -1.00 *** y[0] = 0.04

x[1] = -0.75 *** y[1] = 0.07

x[2] = -0.50 *** y[2] = 0.14

x[3] = -0.25 *** y[3] = 0.39

x[4] = 0.00 *** y[4] = 1.00

x[5] = 0.25 *** y[5] = 0.39

x[6] = 0.50 *** y[6] = 0.14

x[7] = 0.75 *** y[7] = 0.07

推荐阅读