gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 18:12:23 25 4
gpt4 key购买 nike

我有以下代码:

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。

问题是什么?

最佳答案

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

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

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

关于c - 将文件读入结构有时会无缘无故停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36254378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com