所以我正在编写一个程序,将数据从 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;
最佳答案
您使用 MAX_INVENTORY
作为结构体数量和 buf
长度。两者之间没有任何联系。除了结构体数量之外,您还需要定义最大行长度。
如果您有 10 个结构体,但行长度约为 30,那么您只读取了该行的一小部分,解析就会中断,并且可能会发生卡什。
关于c - 将 CSV 文件读取到结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38946488/