尝试从文件中读取数据时出现运行时错误

时间:2013-04-14 23:41:17

标签: c file structure runtime-error

我对逻辑错误有疑问,错误是

"运行时检查失败#2 - 围绕变量'列表'已经腐败了。"

in.txt文件中总共有60行

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define FILE_NAME  20
#define LIST_SIZE 50
//void getData(RECORD name[], RECORD score)


typedef struct 
{
    char *name;
    int  score;
}RECORD;


int main (void)
{
    // Declarations
       FILE *fp;
       char fileName[FILE_NAME];
       RECORD list[LIST_SIZE];
       char buffer[100];
       int count = 0;
       int i;
    // Statements
       printf("Enter the file name: ");
       gets(fileName);

       fp = fopen(fileName, "r");

       if(fp == NULL)
      printf("Error cannot open the file!\n");
       while(fgets(buffer, 100, fp) != NULL)
         {  
         list[count].name = (char*) calloc(strlen(buffer), sizeof(RECORD*));
         if(count > 50)
         {

         }

         if( count < 50)
         {
            sscanf(buffer,"%[^,], %d", list[count].name, &list[count].score);
            for( i =1; i < (50 - count); i++)
            {   
                list[count + i].name = 0;
                list[count + i].score = 0;
            }
         }
         count++;

     }

       printf("Read in %d data records\n", count);
       fclose(fp);
       return 0;
}

在这个程序中我&#39;我试图将数据从文件读取到结构数组,因此如果数据的数量少于50,那么没有数据的结构将为零,如果数据的数量超过50,则程序将只阅读前50个结构。

如何修复运行时错误?

2 个答案:

答案 0 :(得分:0)

如果count = 50,该怎么办?

在while循环中尝试使用以下内容,在开始或结束时引入if块;

if(count >= 50) //count should be checked for >= 50 before being used.
{

}
list[count].name = (char*) calloc(strlen(buffer), sizeof(RECORD*)); //list size is 50 so list[50] won't work. out of bound.

答案 1 :(得分:0)

Perhaps...

while(fgets(buffer, 100, fp) != NULL)
{
  if( count >= 50)
  {
     break;
  }
  if( count < 50)
  {
     list[count].name = (char*) malloc(strlen(buffer)*sizeof(char));
     sscanf(buffer,"%[^,], %d", list[count].name, &list[count].score);
     count++;
  }
}
for( i =0; i < (50 - count); i++)
{   
    list[count + i].name = 0;
    list[count + i].score = 0;
}