所以我正在编写一个程序,将CSV txt文件中的数据转换为数组结构。此数据将用于管理库存。我的整个程序都在运行,但每次运行时它都会崩溃。我的崩溃范围缩小到我的文件阅读功能,并想知道是否有人能看到问题。这是初始文件数据。
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
这是结构减速
struct inventory_s
{
int productNumber;
float mfrPrice;
float retailPrice;
int numInStock;
char liveInv;
char productName[PRODUCTNAME_SZ];
};
结构数组
struct inventory_s inventory[MAX_INVENTORY];
这是我的代码
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;
答案 0 :(得分:0)
您使用MAX_INVENTORY
作为结构数AND和buf
长度。两者之间没有联系。您需要定义除结构数之外的最大行长度。
如果你有10个结构,但是线长约为30,那么你只能阅读该行的一小部分,解析会被中断,并且可能会出现卡片。