我正在尝试从以下形式的文本文件将数据读入结构数组:
代码串
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLINESIZE 300
typedef struct{
int code;
char *name;
}JOB;
int countLines(FILE *fp)
{
int count = 0;
for (int c; (c = fgetc(fp)) != EOF; )
if (c == '\n')
++count;
return count;
}
int main(int argc, char **argv)
{
FILE *fin = fopen("search_file.txt", "r");
if(!fin)
{
fprintf(stderr, "Error opening the file.\n");
exit(EXIT_FAILURE);
}
int nEntries = countLines(fin);
fseek(fin, 0L, SEEK_SET);
//printf("%d", nEntries);
JOB *arr = (JOB *)malloc(nEntries * sizeof(JOB));
int k = 0;
char buf[MAXLINESIZE];
while(!feof(fin))
{
fscanf(fin, "%d", &arr[k].code);
fgetc(fin);
fgets(buf, sizeof(buf), fin);
buf[strlen(buf) - 1] = '\0';
arr[k].name = strdup(buf);
k++;
}
for(k = 0; k < nEntries; k++)
{
printf("[%d] Code : %d | Job: %s\n", k+1, arr[k].code, arr[k].name);
}
fclose(fin);
return 0;
}
现在,它将文件中的代码和字符串存储在相应的成员中,但是在显示文件中的所有内容后,我得到了错误:
损坏的大小与 prev_size
中止(核心转储)
知道为什么会这样吗?
编辑:文本文件示例:
123 something something
456 abc
678 a b c defg