gpt4 book ai didi

c - C中的链表结构与读取txt

转载 作者:行者123 更新时间:2023-11-30 17:03:55 25 4
gpt4 key购买 nike

pitcure

我上传了上面的图片。我问问题,如何从 txt 文件中读取以添加带有结构的链接列表。我尝试这样做,但如何声明basket.txt并生成.txt

FILE *fp
char CustomerName[20];
char CustomerSurname[20];
int CustomerId;
struct Customer *current = NULL, *head = NULL;
fp = fopen("customer.txt", "r");

while (fscanf(fp, "%d\t%s\t%s", &CustomerId, CustomerName, CustomerSurname) != EOF) {
struct Customer *ReadList;
ReadList = (struct Customer *)malloc(sizeof(struct Customer));
ReadList->NextPtr = NULL;
ReadList->CustomerId = CustomerId;
ReadList->CustomerName = strdup(CustomerName);
ReadList->CustomerSurname = strdup(CustomerSurname);
if (head == NULL) {
current = head = ReadList;
} else {
current = current->NextPtr = ReadList;
}
}
fclose(fp);

最佳答案

您的代码中存在一个微妙的问题:解析输入文件的方式不正确:

while (fscanf(fp, "%d\t%s\t%s", &CustomerId, CustomerName, CustomerSurname) != EOF)
  • 您应该通过告诉 fscanf 要存储到这些数组中的最大字符数来防止 CustomerNameCustomerSurname 中的缓冲区溢出:使用 format “%d\t%19s\t%19s”
  • 您只在文件末尾检查 fscanf 是否完全失败,它会返回 EOF,但它会返回已解析的字段数,您应该检查这一点为3。如果fscanf无法解析第一个字段的整数,它将返回0并且所有字段的内容将保持不变。您将无限循环地向列表中添加相同的新记录,直到 malloc 最终返回 NULL(您不进行测试)时崩溃。
  • 格式字符串中的 \t 字符将匹配文件中的任何空白字符序列,而不仅仅是 TAB 字符。这可能与您的预期不同。请注意,%d%s 都忽略前导空白字符,因此格式字符串中的 \t 字符是完全多余的。<

还有其他问题,例如

  • 您没有检查 fopen 失败
  • 您不检查内存分配失败

这是一个改进的版本:

FILE *fp
char CustomerName[20];
char CustomerSurname[20];
int CustomerId;
int res;
struct Customer *current = NULL, *head = NULL;
fp = fopen("customer.txt", "r");
if (fp == NULL) {
fprintf(stderr, "cannot open input file\n");
return 1;
}

while ((res = fscanf(fp, "%d\t%19s\t%19s", &CustomerId, CustomerName, CustomerSurname)) == 3) {
struct Customer *ReadList = malloc(sizeof(*ReadList));
if (ReadList == NULL) {
fprintf(stderr, "cannot allocate memory for customer\n");
fclose(fp);
return 1;
}
ReadList->NextPtr = NULL;
ReadList->CustomerId = CustomerId;
ReadList->CustomerName = strdup(CustomerName);
ReadList->CustomerSurname = strdup(CustomerSurname);
if (ReadReadList->CustomerName == NULL || ReadList->CustomerSurname == NULL) {
fprintf(stderr, "cannot allocate memory for customer fields\n");
fclose(fp);
return 1;
}
if (head == NULL) {
current = head = ReadList;
} else {
current = current->NextPtr = ReadList;
}
}
if (res != EOF) {
fprintf(stderr, "input file has incorrect format\n");
fclose(fp);
return 1;
}
fclose(fp);

关于c - C中的链表结构与读取txt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35975585/

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