Home > Blockchain >  Taking input and output to file using pointer array
Taking input and output to file using pointer array

Time:09-23

Here, the array pointer name[i] is not not working and I can't figure out how to do change the pointer or the array to make it work. There was no compiler error/warning but the console terminal showed negative return value and printf() was not working, and also the output file was created but it was empty. Nothing was written into the output file. I guess theres som problem with the fscanf() action of taking string input from file.

#include<stdio.h>
#include<math.h>

int main()
{
    FILE *fr, *fw;
    fr = fopen("data.txt", "r");
    float wt[10], ht[10], bmi[10];
    char *name[5];
    for(int i = 0; i < 5; i  )
    {
        fscanf(fr, "%s\t%f\t%f", &name[i], &wt[i], &ht[i]);
        bmi[i] = wt[i] / pow(ht[i], 2);
    }
    printf("%s", name[2]);
    fw = fopen("bmi.txt", "w");
    for(int j = 0; j < 5; j  )
    {
        fprintf(fw, "%s\t%f\n", name[j], bmi[j]);
    }
    fclose(fr);
    fclose(fw);
    return 0;
}

 

CodePudding user response:

You should not assume that the file size is 5. You should dynamically allocate memory to the name variable like so:

int length;
fseek(filename, 0, SEEK_END);
length = ftell(filename);
name = malloc(length);
fread(name, 1, length, filename);
  • Related