So I'm writing a program that takes data from a CSV txt file to an array structure. This data will be used to manage an inventory. I had my entire program working, but all of a sudden it crashes every time I run. Iv'e got the crash narrowed down to my file reading function, and was wondering if anyone could see the problem. Here is the initial file data.
1000,1.49,3.79,10,0,Fish Food
2000,0.29,1.59,100,1,Angelfish
2001,0.09,0.79,200,0,Guppy
5000,2.40,5.95,10,0,Dog Collar (Large)
6000,49.99,129.99,3,1,Dalmatian Puppy
Here is the structure deceleration
struct inventory_s
{
int productNumber;
float mfrPrice;
float retailPrice;
int numInStock;
char liveInv;
char productName[PRODUCTNAME_SZ];
};
The structure array
struct inventory_s inventory[MAX_INVENTORY];
Here is the code that I have
FILE* pFile;
char *buf = malloc(MAX_INVENTORY);
char *info;
if ( ( pFile = fopen( "inventory.txt", "r" ) ) == NULL ) //Reading a file
{
printf( "File could not be opened.\n" );
}
int i = 0;
while (fgets(buf, MAX_INVENTORY, pFile) != NULL)
{
if ((strlen(buf)>0) && (buf[strlen (buf) - 1] == '\n'))
buf[strlen (buf) - 1] = '\0';
info = strtok(buf, ",");
inventory[i].productNumber = atoi(info);
info = strtok(NULL, ",");
inventory[i].mfrPrice = atof(info);
info = strtok(NULL, ",");
inventory[i].retailPrice = atof(info);
info = strtok(NULL, ",");
inventory[i].numInStock = atoi(info);
info = strtok(NULL, ",");
inventory[i].liveInv = *info;
info = strtok(NULL, ",");
strcpy(inventory[i].productName, info);
i++;
}
fclose(pFile);
return 0;