需要一些帮助,使用fgets和字符串标记化命令从文本文件中读取数据行,然后使用这些命令创建链表。我遵循了我在Stack Overflow和其他教程网站上找到的一些例子,但仍然不能让下面的read函数在我的程序中正常工作,它只会导致它崩溃。数据文件有如下行:
西葫芦,南瓜,磅,2.19,45
黄色,南瓜,磅,1.79,15
根据我读过的所有内容,我相信我有必要的代码,但显然我遗漏了一些东西。此外,我注释掉了一个字段(一个浮点价格),因为我不确定用什么来从数据中复制浮点值,因为我不能把它当作一个字符串(它下面的整数值似乎让我在我的编译器中摆脱它)。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Struct for linked list node
struct produceItem
{
char produce[20];
char type[20];
char soldBy[20];
float price;
int quantityInStock;
struct produceItem *next;
};
// Function to read in data from file to
void read(struct produceItem **head)
{
struct produceItem *temp = NULL;
struct produceItem *right = NULL;
//char ch[3];
char line[50];
char *value;
FILE *data = fopen("RecitationFiveInput.txt", "r");
printf("Trying to open file RecitationFiveInput.txtn");
if (data == NULL)
{
printf("Could not open file RecitationFiveInput.txtn");
}
else
{
while(fgets(line, sizeof(line), data))
{
value = strtok(line, ", ");
strcpy(temp->produce, strdup(value));
value = strtok(NULL, ", ");
strcpy(temp->type, strdup(value));
value = strtok(NULL, ", ");
strcpy(temp->soldBy, strdup(value));
//value = strtok(NULL, ", ");
//strcpy(temp->price, strdup(value));
value = strtok(NULL, " n");
strcpy(temp->quantityInStock, strdup(value));
temp->next = NULL;
if (*head == NULL)
{
*head = temp;
}
else
{
right = *head;
while(right->next != NULL)
{
right = right->next;
}
right->next = temp;
}
}
printf("Successfully opened file RecitationFiveInput.txtn");
}
fclose(data);
return;
}
// Function to display the nodes of the linked list that contains the data from the data file
void display(struct produceItem *head)
{
int value = 1;
struct produceItem *temp = NULL;
temp = head;
printf("=============================================================================n");
printf(" Item # Produce Type Sold By Price In Stockn");
printf("=============================================================================n");
if(temp == NULL)
{
return;
}
else
{
while(temp != NULL)
{
printf(" %d %s %s %s %lf %dn", value, temp->produce, temp->type, temp->soldBy, temp->price, temp->quantityInStock);
value++;
temp = temp->next;
if(temp == NULL)
{
break;
}
}
}
return;
}
//Main function
int main()
{
int input = 0;
struct produceItem *head = NULL;
while(1)
{
printf("nList Operationsn");
printf("=================n");
printf("1. Stock Produce Departmentn");
printf("2. Display Produce Inventoryn");
printf("3. Reverse Order of Produce Inventoryn");
printf("4. Export Produce Inventoryn");
printf("5. Exit Programn");
printf("Enter your choice: ");
if(scanf("%d", &input) <= 0)
{
printf("Enter only an integer.n");
exit(0);
}
else
{
switch(input)
{
case 1:
read(&head);
break;
case 2:
display(head);
break;
case 3:
//function
break;
case 4:
//function
break;
case 5:
printf("You have exited the program, Goodbye!n");
return 0;
break;
default:
printf("Invalid option.n");
}
}
}
return 0;
}
大家别管了,找到问题了。崩溃是由于我没有为read me函数中的临时指针分配内存。