将多个文本文件读入C中的数组

Reading multiple text files into an array in C

我正在编写一个程序,它可以打开大量文本文件并从中读取行星体的参数。阅读文本文件时遇到问题。

示例文本文件

 2
 1, 1, 2
 3.5, 3, 4

第一个数字 (2) 是指在文件中找到的尸体数量。接下来的两行对应于行星的参数(分别是 x 和 y 坐标以及质量)。我有 4 个文本文件,其中包含不同数量的主体,需要将所有数据存储在一个变量中。

我的代码

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


}

正在读取文本文件中的数字,但是读了6次就停止了,总共有8次。

可能是什么问题?

尝试在第二个 for 循环中用 j = 0 替换 j = count

你的代码有一些问题:

  1. fName 声明为

    char fName[10];
    

    而你使用

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

    将12个字符写入fName(包括NUL-终止符)最多可以容纳9个字符(+1为NUL-终止符)。

  2. for 循环:

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

    有很多问题,也很混乱。当您执行 j = count 时,您检查 j < num。这没有意义,因为 countnum.

  3. 无关

修复:

  1. 第一个问题,分配足够的space给fName:

    char fName[12];
    

    而不是

    char fName[10];
    
  2. 至于第二个问题,用

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