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?
sprintf(fName,"bodies%d.txt",i);<-- Buffer overflow.fNamecan hold a maximum of 9chars +1 for\0at the end. You copy 12chars into it(\0included). Why do you havecount?countrefers to the next position of the arrayj = count, you checkj < num. That's wrong. Usej=0instead ofj = countand it is better to usecount++instead ofcount=j. And in the loop, instead ofb[j], useb[count]. And I don't like your way of hardcoding arrays(unless you know the number of bodies in each file beforehand).struct body *read_body(FILE *fp). and minimise your problem to one single call to this function