c - 将 CSV 文件读取到结构数组

标签 c csv

所以我正在编写一个程序,将数据从 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/

相关文章:

c - 动态分配内存有必要用new吗?

c - 为什么这是返回指针的偏移量? "smashing the stack"

csv - AWS Glue Crawler 无法提取 CSV header

bash - 使用 shell 脚本输出::::而不是实际字符来解析和存储 csv 文件的值

c - 如何在c中迭代列表

android - 使用Android NDK实现EDSDK

php - 使用 PDO 加载 CSV 文件会导致语法错误

sql - 在 SQL Server 2008 中插入/更新大量数据的最佳实践

c - 如何将指向 C(而非 C++)中的结构的指针数组设为空

java - 垂直书写列而不是水平书写