Njal
Njal

Reputation: 13

Reading multiple text files into an array in C

I am writing a program that opens numerous text files and reads from them parameters for planetary bodies. I have a problem when reading the text files.

sample text file

 2
 1, 1, 2
 3.5, 3, 4

The first number (2) refers to the number of bodies found in the file. The next 2 lines correspond to the planet's parameters (x and y coordinates and mass respectively). I have 4 text files containing different amounts of bodies and need to store all the data in a variable.

my code

struct body {

float x;
float y;
float mass;

};

int main()
{

struct body b[8];
FILE *fp;
int i, j, k;
int num, count = 0;
char fName[10];

for (i = 1; i < 5; i++)    
{ 
    sprintf(fName,"bodies%d.txt",i);
    fp = fopen(fName, "r");

    if (fp == NULL)
    {   
        printf("Can't open %s \n",fName);
        exit(-1);
    }

    fscanf(fp, "%d", &num);


    for (j = count; j < num; j++)
    {               
        fscanf(fp, "%f%*c %f%*c %f%*c", &b[j].x, &b[j].y, &b[j].mass);
        printf("%f %f %f\n", b[j].x, b[j].y, b[j].mass);

        count = j;
    }               


}

It is reading the numbers from the text files, but it is stopping after 6 readings and there are 8 in total.

What could be the problem?

Upvotes: 1

Views: 1263

Answers (2)

Spikatrix
Spikatrix

Reputation: 20244

Your code has some problems:

  1. fName is declared as

    char fName[10];
    

    and you use

    sprintf(fName,"bodies%d.txt",i);
    

    which writes 12 characters into fName(including the NUL-terminator) which can atmost hold 9 characters(+1 for the NUL-terminator).

  2. The for loop:

    for (j = count; j < num; j++)
    {               
        fscanf(fp, "%f%*c %f%*c %f%*c", &b[j].x, &b[j].y, &b[j].mass);
        printf("%f %f %f\n", b[j].x, b[j].y, b[j].mass);
    
        count = j;
    }
    

    has many problems and is confusing too. When you do j = count, you check j < num. This makes no sense as count is not related to num.

Fixes:

  1. For the first problem, allocate enough space for fName:

    char fName[12];
    

    instead of

    char fName[10];
    
  2. As for the second problem, use

    for (j = 0; j < num; j++) //j should be initialized to 0
    {               
        fscanf(fp, "%f%*c %f%*c %f%*c", &b[count].x, &b[count].y, &b[count].mass);
        printf("%f %f %f\n", b[count].x, b[count].y, b[count].mass); //Use b[count] instead of b[j]
    
        //count = j; Works, but the below is better
        count++;
    }
    

Upvotes: 1

fassl
fassl

Reputation: 754

Try replacing j = count with j = 0 in the second for loop.

Upvotes: 1

Related Questions