将文件读入结构有时会无缘无故地停止

时间:2016-03-28 00:47:15

标签: c clion

我有以下代码:

int main() {    
    FILE *fp = fopen("inventory.txt", "r");
    if (fp == NULL) {
        printf("File Error");
        return 1;
    }

    while (1) {
        char *componentType = malloc(200);
        char *stockCode = malloc(20);
        int numberOfItems = 0;
        int price = 0;
        char *additionalInformation = malloc(20);

        int fileRead = fscanf(fp, "%[^,], %[^,], %i, %i, %[^,\r\n]", componentType, stockCode, &numberOfItems, &price,
                              additionalInformation);

        if (fileRead == EOF) {
            printf("End of file!\n");
            break;
        }

        printf("%s Read Record!\n", stockCode);

        free(componentType);
        free(stockCode); 
        free(additionalInformation);
    }

    printf("DONE!");
    fclose(fp);

}

该文件如下所示:

resistor, RES_1R0, 41, 1, 1R0
resistor, RES_10R, 467, 1, 10R
resistor, RES_100R, 334, 1, 100R
resistor, RES_1K0, 500, 1, 1K0
resistor, RES_10K, 169, 1, 10K
resistor, RES_100K, 724, 1, 100K
resistor, RES_1M0, 478, 1, 1M0
diode, BY126, 118, 12
diode, BY127, 45, 12
transistor, AC125, 13, 35, PNP
transistor, AC126, 40, 37, PNP
....

但是,当我运行代码时,它有时会像这样完成:

RES_1R0 Read Record!
RES_10R Read Record!
...
CF12 Read Record!
CF13 Read Record!
Done!

但有时它会毫无理由地停止:

RES_1R0 Read Record!
RES_10R Read Record!
...
D12 Read Record!
D13 Read

每次它仍然返回0.

有什么问题?

2 个答案:

答案 0 :(得分:0)

自从我第一次提出这个问题以来,这个问题已经发生了很大变化(首先我认为这是一个内存/结构问题,然后它成了一个编译器问题,然后我终于发现它是一个IDE问题),因此我决定完全提出一个新问题:Output for CLion IDE sometimes cuts off when executing a program

这个具体问题的答案是这是CLion IDE的一个问题。要解决此问题,请使用终端编译并运行代码,输出正常。

感谢@Dominik Gebhar& @Jonathan Leffler的帮助!!!

答案 1 :(得分:-1)

fscanf()会返回读取的字符数或文件末尾的零,而 fgetc(fp)会在到达文件末尾时返回字符或EOF。

您正在混合两种eof检测方法。