/******************************************************************************
Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, PHP, Ruby,
C#, VB, Perl, Swift, Prolog, Javascript, Pascal, HTML, CSS, JS
Code, Compile, Run and Debug online from anywhere in world.
*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
struct node
{
char name[10];
int quan;
int price;
struct node* link;
};
struct node* root = NULL;
void append(void);
void display(void);
void save(void);
void load(void);
int main()
{
int ch;
while(1)
{
printf("Single Liked list Operations: \n");
printf("1. Append\n");
printf("2. Display\n");
printf("3. Save\n");
printf("4. Load\n");
printf("5. Quit\n");
printf("Enter your choice: \n");
scanf("%d", &ch);
switch(ch)
{
case 1: append();
break;
case 2: display();
break;
case 3: save();
break;
case 4: load();
case 5: exit(1);
default: printf("Invalid input\n\n");
}
}
return 0;
}
void append()
{
struct node* temp;
temp = (struct node*)malloc(sizeof(struct node));
printf("Enter node Quantity: ");
scanf("%d", &temp->quan);
printf("Enter node Price: ");
scanf("%d", &temp->price);
getchar();
printf("Enter name: ");
fgets(temp->name, 9, stdin);
temp->link = NULL;
if(root == NULL) //list is empty
{
//temp = root;
root = temp;
}
else
{
struct node* p;
p = root;
while(p->link != NULL)
{
p = p->link;
}
p->link = temp;
}
}
void display()
{
struct node* temp;
temp = root;
if(temp == NULL)
{
printf("list is empty \n\n");
}
else
{
while(temp != NULL)
{
printf("\nantal: %d -->", temp->quan);
//printf("\n");
printf("\npris: %d -->", temp->price);
printf("\nnamn: %s -->", temp->name);
temp = temp->link;
}
printf("\n\n");
}
}
//Load the catalog file ----- THIS I HAVE PROBLEM WITH!!!
void load(void)
{
struct node* temp;
temp = root;
temp = (struct node*)malloc(sizeof(struct node));
//root = temp;
FILE *fp;
if((fp = fopen("catalog.txt", "r"))==NULL)
{
printf("Cannot open catalog file\n");
exit(1);
}
temp = (struct node*)malloc(sizeof(struct node));
if(temp == NULL)
{
printf("list is empty \n\n");
}
else
{
while(temp != NULL)
{
//fread(&temp, sizeof(temp), 1, fp);
//fscanf(&temp, sizeof(temp), 1, fp);
fscanf(fp, "%s", temp->name); // line = &line[0]
fscanf(fp, "%d", &temp->quan);
fscanf(fp, "%d", &temp->price);
temp = temp->link;
}
printf("\n\n");
fclose(fp);
}
}
//Save the catalog file
void save(void)
{
struct node* temp;
temp = root;
temp = (struct node*)malloc(sizeof(struct node));
FILE *fp;
if((fp = fopen("catalog.txt", "w"))==NULL)
{
printf("Cannot open catalog file\n");
exit(1);
}
if(temp == NULL)
{
printf("list is empty \n\n");
}
else
{
while(temp != NULL)
{
fprintf(fp, "%d\n", temp->quan);
printf("\n");
fprintf(fp, "%d\n", temp->price);
printf("\n");
fprintf(fp, "%s\n", temp->name);
printf("\n");
temp = temp->link;
}
printf("\n\n");
fclose(fp);
}
}