I'm trying to read data into an array of structs from a text file of the form:
code string
#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;
}
Right now, it's storing the code and the string from the file inside the corresponding members, but after displaying everything from the file, I get the error:
corrupted size vs. prev_size
Aborted (core dumped)
Any idea why this is happening?
EDIT: text file example:
123 something something
456 abc
678 a b c defg