将数据从文本文件保存到结构中

时间:2015-11-22 19:04:12

标签: c pointers io

我正在尝试为我正在阅读的此文件中的第一行之后的每一行创建一个新的test_type_t结构。然后我想将新结构保存在一个集合中以供以后使用。

目前我遇到了以下情况发生的问题。请注意,第一个SKU行实际上是文件的第二行。

首先阅读SKU行 - >新P(1)创建 - > P(1)填充数据 - > P(1)添加到set = productlist-> head-> data = P(1)

第二SKU行读 - >新P(2)创建 - > P(2)填充数据 - > P(2)加到set = productlist-> head-> data = P(2)

这导致我失去了P(1)的数据。

我知道set_add正常运行,因为代码已经过测试并提供给我。我几乎可以肯定,我只是搞砸了一些指针逻辑。以下是相关代码:

// See how this goes I feel like 100 is overkill
char *line = (char *)malloc(100);
int count = 0;

if (inputFromFile) {
    inputFile = fopen(inputFileName, "r");

    if (inputFile != NULL) {
        while (fgets(line, 50, inputFile) != NULL) {
            if (count == 0) {
                strncpy(order.customerID,line, 12);
            } else {
                // Prodcut p really
                test_type_t *pPointer = (test_type_t *)malloc(
                        sizeof(test_type_t));
                test_type_t p = *pPointer;
                char *token;

                token = strtok(line, "\t");
                strncpy(p.SKU, token, 12);

                token = strtok(NULL, "\t");
                p.quantity = atoi(token);

                set_add(productList, &p);
            }

            // Do something with the line
            count++;
        }

        fclose(inputFile);
    }

0 个答案:

没有答案