0

i'm a newbie on c and i want to check if i have understood how funtions for file handling does work, here is my code. the issue that i faced is the evaluation of fx in every x is stored successfully on the file pointinterpol.dat, but when i want to read to stores its contents on the two array and print them, i got all elements of x,y arrays zero. I don't know what is going wrong ?

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;
}
Govind Parmar
  • 20,656
  • 7
  • 53
  • 85
  • `fclose()` the file **before** `fopen()` it for the 2nd time. As it stands, the code has the same file opened for writing and reading at the same time. Remember to `#include `! – pmg Oct 14 '20 at 16:05
  • Thanks a lot, yes i must focus more –  Oct 14 '20 at 18:27

1 Answers1

1

As pointed out in comments, you need to call fclose() once you're done with writing data to the file. I added fclose() just after first while loop and I was able to see expected output:

#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;
}

When I run this, I get this output:


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
Rohan Kumar
  • 5,427
  • 8
  • 25
  • 40