Error while printing the linked list - c

I created the linked list to store employee id and name.
When I tried to print it, it shows only id not an employee name and i also want to exit the program when the user enter -1 and not asking the name its should simply exit the program and display the id and name i am currently using devC++ for compiling my code
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node
{
int id;
char name[20];
struct node *next;
};
struct node *create()
{
struct node *p, *r, *n;
int s, k;
char name[20];
s = sizeof(struct node);
printf("Linked List\n");
printf("Enter id:");
scanf("%d", &k);
printf("Enter name:");
scanf("%s", name);
p = r = NULL;
while(k!=-1)
{
n = (struct node *)malloc(s);
n->id = k;
n->next = NULL;
if(r == NULL)
r = n;
else
p->next=n;
p=n;
printf("Enter the Id or-1 to stop:");
scanf("%d", &k);
printf("Enter the name ");
scanf("%s", name);
}
return(r);
}
void display(struct node *r)
{
printf("\nId Name \n");
while(r != NULL)
{
printf("\n %d", r->id);
printf("\n %s", r->name);
r = r->next;
}
}
int main()
{
struct node *ptr;
ptr = create();
display(ptr);
}

You actually read in the name variable, but you don't move it in your structure.
That said, you could directly read into the structure you allocate, but the tricky part is taking care of not overflowding your buffer when the user input is too big (more than 19 chars).
This could look like this:
#include<stdio.h>
#include<stdlib.h>
struct node {
int id;
char name[20];
struct node *next;
};
struct node *create(void) {
struct node *p, *r;
printf("Linked List\n");
p = r = NULL;
while (1) {
int id;
printf("Enter the Id or-1 to stop:");
scanf("%d", &id);
if (id == -1)
break; // user asked to leave
struct node *n = malloc(sizeof(*n));
// if (n == NULL) exit(-1); as you prefere...
n->id = id;
printf("Enter the name ");
// careful of buffer overflow here
scanf("%19s%*[^\n]", n->name);
n->next = NULL;
if (r == NULL)
r = n;
else
p->next = n;
p = n;
}
return r;
}
void delete(struct node *r) {
while (r != NULL) {
struct node *n = r;
r = r->next;
free(n);
}
}
void display(const struct node *r) {
printf("\nId Name \n");
while (r != NULL) {
printf("%d %s\n", r->id, r->name);
r = r->next;
}
}
int main(int argc, char **argv) {
struct node *ptr = create();
display(ptr);
delete(ptr);
return 0;
}
As a bonus, I also added the free part so that you don't leak.

Related

C QueueLinkedList string variable not working

#include<stdlib.h>
struct customer
{
int phoneNum;
char *name;
struct customer *nxt;
};
struct customer *initialNode(int i, char *n);
int isEmpty(struct customer *head, struct customer *tail);
void enqueue(int phNum1, char *cName1, struct customer *tail);
void dequeue(struct customer *head, struct customer *tail);
void display(struct customer *head, struct customer *tail);
int main()
{
int phNum;
char *cName;
int choice;
struct customer *head;
struct customer *tail;
head = initialNode(0, NULL);
tail = initialNode(0, NULL);
head->nxt = tail;
tail->nxt = head;
while (choice !=4)
{
printf("\nEnter your option:");
printf("\n1. Enqueue new customer. \n2. Dequeue customer. \n3. Display customer in queue. \n4. Exit. \nOption: ");
scanf("%d", &choice);
switch(choice)
{
case 1:
{
printf("\nEnter customer phone number: ");
scanf("%d", &phNum);
printf("\nEnter customer name: ");
scanf("%s", cName);
enqueue(phNum, cName, tail);
break;
}
case 2:
{
dequeue(head, tail);
break;
}
case 3:
{
display(head, tail);
break;
}
default:
{
if (choice < 1 || choice > 4)
printf("\nInvalid option!\n");
break;
}
}
}
}
struct customer *initialNode(int i, char *n)
{
struct customer *newCustomer = malloc(sizeof(struct customer));
newCustomer->phoneNum = i;
newCustomer->name = n;
newCustomer->nxt = NULL;
return newCustomer;
}
int isEmpty ( struct customer *head, struct customer *tail)
{
if (head->nxt == tail)
return 1;
else
return 0; //cannot is full because it is not array, have no size limitation
}
void enqueue(int phNum1, char *cName1, struct customer *tail)
{
struct customer *nC = malloc(sizeof(struct customer));
nC = initialNode(phNum1, cName1);
nC->nxt = tail;
tail->nxt->nxt = nC;
tail->nxt = nC;
printf("\nSuccessfully enqueue a customer!\n");
}
void dequeue(struct customer *head, struct customer *tail)
{
struct customer *removedCustomer = malloc(sizeof(struct customer));
if (isEmpty(head, tail) == 1)
{
printf("\nThe queue is empty!\n");
}
else
{
removedCustomer = head->nxt;
printf("\nFirst customer is removed.\n");
head->nxt = head->nxt->nxt;
}
}
void display(struct customer *head, struct customer *tail)
{
struct customer *tempH = malloc(sizeof(struct customer));
tempH = head;
tempH = tempH->nxt;
if (isEmpty(head, tail) == 1)
{
printf("\nThe queue is empty!\n");
}
else
{
printf("\n===Current customer list===");
while (tempH != tail)
{
printf("\n\tCustomer phone number : %d", tempH->phoneNum);
printf("\n\tCustomer name: %s\n", tempH->name);
tempH = tempH->nxt;
}
}
}
The code is suppose to make queue of a list of customer that user input their phone number and name, code is working well but when i input a new customer, the customer before's name all somehow become the latest customer's name..
How do i solve this? Do i declare a 2D string array to collect different set of customer's name?
I see the below issues with the code.
The head and tail should be initialized to NULL. This signifies an empty list.
In the initialnode function you are directly assigning the scanned pointer as newCustomer->name = n. This is wrong. As you have declared the struct as having a character pointer, you need to also allocate space for each string separately.
The enqueue and dequeue functions can change the value of the head and tail pointers in the main function. You can change the function declarations to pass a double pointer for this.
You also need to free the struct on dequeue. This is strictly not necessary in a small program but is a good practice anyway to avoid memory leaks in larger programs.
In the display function you are having an unnessary malloc which needs to be removed. This function does not need to allocate memory.
The variable choice in main is not initailized.
Please see the code below
#include<stdlib.h>
#include <stdio.h>
#include <string.h>
struct customer
{
int phoneNum;
char *name;
struct customer *nxt;
};
struct customer *initialNode(int i, char *n);
int isEmpty(struct customer *head, struct customer *tail);
void enqueue(int phNum1, char *cName1, struct customer **head, struct customer **tail);
void dequeue(struct customer **head, struct customer **tail);
void display(struct customer *head, struct customer *tail);
int main(void)
{
int phNum;
char cName[51]; // max name length supported
int choice = 0;
struct customer *head;
struct customer *tail;
head = NULL;
tail = NULL;
while (choice !=4)
{
printf("\nEnter your option:");
printf("\n1. Enqueue new customer. \n2. Dequeue customer. \n3. Display customer in queue. \n4. Exit. \nOption: ");
scanf("%d", &choice);
switch(choice)
{
case 1:
{
printf("\nEnter customer phone number: ");
scanf("%d", &phNum);
printf("\nEnter customer name: ");
scanf("%s", cName);
enqueue(phNum, cName, &head, &tail);
break;
}
case 2:
{
dequeue(&head, &tail);
break;
}
case 3:
{
display(head, tail);
break;
}
default:
{
if (choice < 1 || choice > 4)
printf("\nInvalid option!\n");
break;
}
}
}
return 0;
}
struct customer *initialNode(int i, char *n)
{
int len;
struct customer *newCustomer = malloc(sizeof(struct customer));
newCustomer->phoneNum = i;
len = strlen(n);
newCustomer->name = malloc(len +1);
strcpy(newCustomer->name, n);
newCustomer->nxt = NULL;
return newCustomer;
}
int isEmpty ( struct customer *head, struct customer *tail)
{
if ((head == NULL) && (tail == NULL))
return 1;
else
return 0; //cannot is full because it is not array, have no size limitation
}
void enqueue(int phNum1, char *cName1, struct customer **head, struct customer **tail)
{
struct customer *nC = malloc(sizeof(struct customer));
nC = initialNode(phNum1, cName1);
if (isEmpty(*head,*tail))
{
*head = nC;
*tail = nC;
}
else if (*head == *tail) // single element
{
(*head)->nxt = nC;
*tail = nC;
}
else
{
(*tail)->nxt = nC;
*tail = nC;
}
printf("\nSuccessfully enqueue a customer!\n");
}
void dequeue(struct customer **head, struct customer **tail)
{
struct customer *removedCustomer = malloc(sizeof(struct customer));
if (isEmpty(*head, *tail) == 1)
{
printf("\nThe queue is empty!\n");
}
else if (*head == *tail) // single element
{
removedCustomer = *head;
free(removedCustomer->name);
free(removedCustomer);
*head = NULL;
*tail = NULL;
}
else
{
removedCustomer = *head;
*head = (*head)->nxt;
free(removedCustomer->name);
free(removedCustomer);
printf("\nFirst customer is removed.\n");
}
}
void display(struct customer *head, struct customer *tail)
{
struct customer *tempH;
tempH = head;
if (isEmpty(head, tail) == 1)
{
printf("\nThe queue is empty!\n");
}
else
{
printf("\n===Current customer list===");
while (tempH != NULL)
{
printf("\n\tCustomer phone number : %d", tempH->phoneNum);
printf("\n\tCustomer name: %s\n", tempH->name);
tempH = tempH->nxt;
}
}
}

Using fwrite() to write structure within queue structure into binary file

I want to write a struct from queue (data structure) struct using fwrite() into a binary file.
struct addressbook
{
char first[15];
char surname[15];
char address[60];
char city[15];
char country[15];
char zip[6];
char phone[15];
char mob[15];
};
struct node
{
struct addressbook data;
struct node *next;
};
struct node *front = NULL;
struct node *rear = NULL;
My code is as follows:
void writedata (void)
{
FILE *fp;
char CONTINUE;
struct addressbook blank;
struct node *temp;
fp = fopen("asdf.dat","ab");
while(1)
{
temp = (struct node*)malloc(sizeof(struct node));
if (temp != NULL)
{
fflush(stdin);
printf("\nEnter First name?\n");
gets(temp->data.first);
printf("Enter Surname?\n");
gets(temp->data.surname);
printf("Enter Street Address (with commas)?\n");
gets(temp->data.address);
printf("Enter City?\n");
gets(temp->data.city);
printf("Enter Country?\n");
gets(temp->data.country);
printf("Enter Zipcode?\n");
gets(temp->data.zip);
printf("Enter Phone number?\n");
gets(temp->data.phone);
printf("Enter Mobile number?\n");
gets(temp->data.mob);
temp->next = NULL;
fwrite(&temp->data,sizeof(struct addressbook),1,fp);
if (front == NULL)
{
front = temp;
}
else
{
rear->next = temp;
}
rear = temp;
}
else
{
printf( "No memory available.\n");
}
printf("CONTINUE\nY-YES \nN-NO\n? ");
fflush(stdin);
CONTINUE = getchar();
if (CONTINUE == 'N' || CONTINUE == 'n')
break;
}
fclose(fp);
}
I am getting garbage value at the output.

printing the nodes in linked list in c

here is a program which inserting 2 names 2 paths and 2 duration s into linked list (struct of linked lists) , printing them and swapping between them when the duration of the first node is 8.
but when the program printing the nodes its prints from all of the nodes the name and the path of the last node
please help me
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Frame
{
char *name;
unsigned int duration;
char *path; // may change to FILE*
}*n3;
typedef struct Frame frame_t;
struct Link
{
frame_t *frame;
struct Link *next;
}*n ;
typedef struct Link link_t;
struct Link* insert(struct Link *n3);
void print(struct Link* head, int flag);
void swap(struct Link **head, int value);
#define MAX_PATH_SIZE (256)
#define MAX_NAME_SIZE (50)
int main()
{
struct Link* head = NULL;
int flag = 0;
int num = 0;
char namearray[MAX_NAME_SIZE] = { 0 };
char patharray[MAX_PATH_SIZE] = { 0 };
printf("1\n");
printf("\n");
for (int i = 0; i < 2; i++)
{
printf("Enter a number you want to insert - ");
scanf("%d", &num);
printf("\nEnter the name - ");
scanf("%s", &namearray);
printf("\nEnter the path - ");
scanf("%s", &patharray);
printf("\n");
head = insert(head,num,namearray,patharray);
}
print(head, flag);
swap(&head, 8);
printf("1\n");
system("pause");
return 0;
}
struct Link *insert(struct Link *p, int n, char namearray[MAX_NAME_SIZE], char patharray[MAX_PATH_SIZE]) //insert func
{
struct node *temp;
if (p == NULL) //if the node is empty
{
p = (struct Link *)malloc(sizeof(struct Link)); //gives memory to the node
p->frame = (struct Frame *)malloc(sizeof(struct Frame));
if (p == NULL)
{
printf("Error\n");
}
else
{
printf("The number added to the end of the list\n");
}
p->frame->duration = n; //its runing untill the node item is NULL
p->frame->name = namearray;
p->frame->path = patharray;
p->next = NULL;
}
else
{
p->next = insert(p->next, n , namearray , patharray);/* the while loop replaced by
recursive call */
}
return (p);
}
void print(struct Link* head , int flag)//print func
{
if (head == NULL && flag == 0) //if the node is empty
{
printf("The list is empty\n");
return 1;
}
if (head == NULL && flag != 0) //if the node isnt empty but we are in the NULL (last) item of the node
{
printf("\n");
printf("the nodes of the list printed\n");
return;
}
printf("%d ", head->frame->duration);//prints the currect item
printf("\n");
printf("%s ", head->frame->name);//prints the currect item
printf("\n");
printf("%s ", head->frame->path);//prints the currect item
printf("\n");
print(head->next, ++flag);//calls the func recursevly
return 1;
}
void swap(struct Link **head, int value)
{
while (*head && (*head)->frame->duration != value)
{
head = (*head)->next;
}
if (*head && (*head)->next)
{
struct list *next = (*head)->next->next;
(*head)->next->next = *head;
*head = (*head)->next;
(*head)->next->next = next;
}
}
here is the print :
the print of the program

C: Read Struct into Link List (from File)

I am new to C programming. I have created a student database to enter student details into a linked list (in the form of structure "phbook") and save linked list onto text file. The part I cannot get to work is to read the text file records onto the linked list. The program runs but does not update the linked list when I close the program then select to "LOAD FROM EXTERNAL FILE". Please can someone help me figure what the problem is. I know everything worked until I coded the "readFile" and "insertFull" function. Friends have told me that the global variable "struct phbook *list = NULL;is causing the problem. Please let me know.
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
struct phbook{
int number;
char name[20];
int mark;
struct part *next;
};
struct phbook *list = NULL;
struct phbook *find_student(int number);
void insertFull(struct phbook* list, int number, char Name[10],int mark);
int main(void)
{
int code;
int opt1;
int courses, i, k, j, counter;
for (;;){
printf("Enter operation code: \n");
printf("(1) ADD NEW STUDENT DETAILS: \n");
printf("(2) SEARCH STUDENT DETAILS: \n");
printf("(3) DISPLAY REPORT OF ALL STUDENTS: \n");
printf("(4) SAVE ALL STUDENT RECORDS TO EXTERNAL FILE: \n");
printf("(5) LOAD ALL STUDENT RECORDS FROM EXTERNAL FILE: \n");
scanf(" %d", &code);
switch (code){
case 1 : insert();
break;
case 2 : search();
break;
break;
case 3 : print();
break;
case 4 :
saveToFile();
break;
case 5 :
readFile();
break;
default: printf("Illegal code\n");
}
printf("\n");
}
}
struct phbook *find_student(int number)
{
struct phbook *p;
for (p = list; p != NULL && number != p->number; p = p->next);//was sorted
if (p != NULL && number == p->number)
return p;
return NULL;
}
void insert(void)
{
struct phbook *cur;
struct phbook *prev;
struct phbook *new_node;
new_node = (struct phbook*) malloc(sizeof(struct phbook));
if (new_node == NULL){
printf("db full er1.\n");
return;
}
printf("enter student id");
scanf("%d", &new_node->number);
for (cur = list, prev = NULL; cur!= NULL && new_node->number > cur->number; prev = cur, cur = cur->next);
printf("Enter name: ");
scanf("%s", &new_node->name);//readline(new_node->name, NAME_LEN)
printf("Enter MARK: ");
scanf("%d", &new_node->mark);
new_node->next = cur;
if (prev == NULL)
list = new_node;
else
prev->next = new_node;
}
void search(void)
{
int number;
struct phbook *p;
printf("Enter ID: ");
scanf("%d", &number);
p = find_student(number);
if (p != NULL){
printf("Name: %s\n", p->name);
printf("Marks: %d\n", p->mark);
}
else
printf("student not found.\n");
}
void print(void)
{
struct phbook *p;
printf("Student_Number Student_Name Student_Mark\n");
for (p = list; p != NULL; p = p->next)
printf("%7d %-25s %d\n", p->number, p->name, p->mark);
}
void saveToFile()
{
FILE* fp;
fp = fopen ("results.txt","w");
struct phbook* curr = list;//he
while(curr!=NULL)
{
fprintf(fp,"%s\n", list->name);
fprintf(fp,"%d\n",curr->number);
fprintf(fp, "%d\n", curr->mark);
curr = curr->next;
}
fclose(fp);
}
void readFile()
{
FILE* fp;
if (!(fp = fopen ("results.txt", "r")))
printf("File NOT Found");
else{
struct phbook *curr;
struct phbook *prev;
char TempName[10];
int TempNumber;
int TempMark;
int done = 0;
int count = 0;
int success;//dummy
curr = list;//sets it to the head (first nde of ll)
if(list == NULL);
printf("List is null\n");
if(curr == NULL)
printf("List is null\n");
while (curr!=NULL)
{
curr = curr->next;
}
while (done == 0)
{
success = fscanf(fp, "%s", TempName);
if (success == 1)
{
success = fscanf(fp, "%d", &TempNumber);
if (success == 1)
{
success = fscanf(fp, "%d", &TempMark);
if(success == 1)
{
insertFull(list,TempNumber,TempName,TempMark);
}
}
}
else
{
done = 1;
}
}
}
}
void insertFull(struct phbook* list, int number, char Name[10],int mark)
{
struct phbook *cur;
struct phbook *prev;
struct phbook *new_node;
new_node = (struct phbook*) malloc(sizeof(struct phbook));
if (new_node == NULL){
printf("db full er1.\n");
return;
}
for (cur = list, prev = NULL; cur!= NULL && new_node->number > cur->number; prev = cur, cur = cur->next);
new_node->number = number;
new_node->mark = mark;
strcpy(new_node->name,Name);
new_node->next = cur;
if (prev == NULL)
list = new_node;
else
prev->next = new_node;
}
In the procedure
void insertFull(struct phbook* list, int number, char Name[10],int mark)
you are changing your local copy of list, this has no effect on the global phone book list.
You can remove list from the argument lists, thus changing the global variable:
void insertFull(int number, char Name[10],int mark)
this is not strictly good programming, but it is in line with the rest of your code.

how to copy txt file (containing structs) to linked list c

I am new to c programming. In my program I have to make a database to store students. The program has to allow to enter marks, id, name and store (as struct)in linked list and also store in file and also read from file into linked list. The only problem I have is that when I close the .exe program and then select to read from .txt file into linked list it does not work. No errors came when I compiled the code but when I AFTERWARDS select DISPLAY REPORT OF ALL STUDENTS no records are shown. This is a minor problem, please suggest how to fix this.
My code is as follows:
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
struct phbook
{
int number;
char name[20];
int mark;
struct part *next;
};
//struct phbook *find_student(int number);
//void insertFull(struct phbook* list, int number, char Name[10],int mark);
struct phbook* insert(struct phbook *list);
struct phbook* insertFull(struct phbook* list,
int number,
char Name[10],
int mark);
void readFile(struct phbook* list);
int main(void)
{
struct phbook *list = NULL;
int code;
int opt1;
int courses, i, k, j, counter;
for (;;)
{
printf("Enter operation code: \n");
printf("(1) ADD NEW STUDENT DETAILS: \n");
printf("(2) SEARCH STUDENT DETAILS: \n");
printf("(3) DISPLAY REPORT OF ALL STUDENTS: \n");
printf("(4) SAVE ALL STUDENT RECORDS TO EXTERNAL FILE: \n");
printf("(5) LOAD ALL STUDENT RECORDS FROM EXTERNAL FILE: \n");
scanf(" %d", &code);
switch (code)
{
case 1:
list = insert(list);
break;
case 2: //search();
break;
break;
case 3:
print(list);
break;
case 4:
saveToFile(list);
break;
case 5:
readFile(list);
break;
default:
printf("Illegal code\n");
}
printf("\n");
}
}
/*struct phbook *find_student(int number)
{
struct phbook *p;
for (p = list; p != NULL && number != p->number; p = p->next);//was sorted
if (p != NULL && number == p->number)
return p;
return NULL;
}*/
struct phbook* insert(struct phbook *list)
{
struct phbook *cur;
struct phbook *prev;
struct phbook *new_node;
new_node = (struct phbook*) malloc(sizeof(struct phbook));
if (new_node == NULL)
{
printf("db full er1.\n");
return NULL;
}
printf("enter student id");
scanf("%d", &new_node->number);
for (cur = list, prev = NULL; cur != NULL && new_node->number > cur->number;
prev = cur, cur = cur->next)
;
printf("Enter name: ");
scanf("%s", &new_node->name); //readline(new_node->name, NAME_LEN)
printf("Enter MARK: ");
scanf("%d", &new_node->mark);
new_node->next = cur;
if (prev == NULL)
list = new_node;
else
prev->next = new_node;
return list;
}
void search(void)
{
int number;
struct phbook *p;
printf("Enter ID: ");
scanf("%d", &number);
p = find_student(number);
if (p != NULL)
{
printf("Name: %s\n", p->name);
printf("Marks: %d\n", p->mark);
}
else
printf("student not found.\n");
}
void print(struct phbook *list)
{
struct phbook *p;
printf("Student_Number Student_Name Student_Mark\n");
for (p = list; p != NULL; p = p->next)
printf("%7d %-25s %d\n", p->number, p->name, p->mark);
}
void saveToFile(struct phbook *list)
{
FILE* fp;
fp = fopen("results.txt", "w");
struct phbook* cur = list; //he
while (cur != NULL)
{
fprintf(fp, "%s\n", list->name);
fprintf(fp, "%d\n", cur->number);
fprintf(fp, "%d\n", cur->mark);
cur = cur->next;
}
fclose(fp);
}
void readFile(struct phbook* list)
{
FILE* fp;
if (!(fp = fopen("results.txt", "r")))
printf("File NOT Found");
else
{
struct phbook *cur;
struct phbook *prev;
char TempName[10];
int TempNumber;
int TempMark;
int done = 0;
int count = 0;
int success; //dummy
cur = list; //sets it to the head (first nde of ll)
if (list == NULL)
;
printf("List is null\n");
if (cur == NULL)
printf("List is null\n");
while (cur != NULL)
{
cur = cur->next;
}
while (done == 0)
{
success = fscanf(fp, "%s", TempName);
if (success == 1)
{
success = fscanf(fp, "%d", &TempNumber);
if (success == 1)
{
success = fscanf(fp, "%d", &TempMark);
if (success == 1)
{
insertFull(list, TempNumber, TempName, TempMark);
}
}
}
else
{
done = 1;
}
}
}
}
struct phbook* insertFull(struct phbook* list,
int number,
char Name[10],
int mark)
{
struct phbook *cur;
struct phbook *prev;
struct phbook *new_node;
new_node = (struct phbook*) malloc(sizeof(struct phbook));
if (new_node == NULL)
{
printf("db full er1.\n");
return;
}
for (cur = list, prev = NULL; cur != NULL && new_node->number > cur->number;
prev = cur, cur = cur->next)
;
new_node->number = number;
new_node->mark = mark;
strcpy(new_node->name, Name);
new_node->next = cur;
if (prev == NULL)
list = new_node;
else
prev->next = new_node;
return list;
}
the screenshot is this:
Screen shot was already MIA when I got here - user4581301
If you execute your application the main list will be null.
When you then call readFile(), you will not update the list in main. You just pass the pointer by value, so that you'll update the local paramater of that function. By the way, the call to insertFull() has the almost the same problem: it returns the list following the insertion, but you ignore this return.
Change these two functions, so that they both return the list, like you do for insert():
struct phbook* readFile(struct phbook* list)
{
...
list = insertFull(list, TempNumber, TempName, TempMark);
...
return list;
}
and of course adapt your function prototype at the beginning, and updated the menu handling:
case 5:
list = readFile(list);
break;
the following code compiles cleanly
However, it will not link because the function: find_student() is commented out.
Examination of the code indicates it will not fully perform all the desired functionality. So you will still have to debug the execution.
Suggest using a debugger, like gdb
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_NAME_LEN (20)
struct phbook
{
int studentID;
char studentName[ MAX_NAME_LEN ];
int studentGrade;
struct phbook *next;
};
// prototypes
struct phbook* insert(struct phbook* );
struct phbook* find_student( int );
void insertFull( struct phbook*, int, char *, int );
void readFile ( struct phbook* );
void print ( struct phbook* );
void saveToFile( struct phbook* );
int main(void)
{
struct phbook *list = NULL;
int code;
for (;;)
{
printf("Enter operation code: \n");
printf("(1) ADD NEW STUDENT DETAILS: \n");
printf("(2) SEARCH STUDENT DETAILS: \n");
printf("(3) DISPLAY REPORT OF ALL STUDENTS: \n");
printf("(4) SAVE ALL STUDENT RECORDS TO EXTERNAL FILE: \n");
printf("(5) LOAD ALL STUDENT RECORDS FROM EXTERNAL FILE: \n");
scanf(" %d", &code);
switch (code)
{
case 1:
list = insert(list);
break;
case 2: //search();
break;
break;
case 3:
print(list);
break;
case 4:
saveToFile(list);
break;
case 5:
readFile(list);
break;
default:
printf("Illegal code\n");
} // end switch
printf("\n");
} // end for()
} // end function: main
#if 0
struct phbook *find_student(int studentID)
{
struct phbook *p;
for (p = list; p != NULL && studentID != p->studentID; p = p->next);//was sorted
return p;
} // end function: find_student
#endif
struct phbook* insert(struct phbook *list)
{
struct phbook *cur;
struct phbook *prev;
struct phbook *new_node;
if( NULL == (new_node = malloc(sizeof(struct phbook)) ) )
{
perror( "malloc for struct phbook failed");
return NULL;
}
// implied else malloc successful
printf("enter student id");
scanf("%d", &new_node->studentID);
for (cur = list, prev = NULL;
cur != NULL && new_node->studentID > cur->studentID;
prev = cur, cur = cur->next)
{
;
}
printf("Enter studentName: ");
scanf("%19s", new_node->studentName); //readline(new_node->studentName, NAME_LEN)
printf("Enter MARK: ");
scanf("%d", &new_node->studentGrade);
new_node->next = cur;
if (!prev)
{
list = new_node;
}
else
{
prev->next = new_node;
}
return list;
} // end function: search
void search(void)
{
int studentID;
struct phbook *p;
printf("Enter ID: ");
scanf("%d", &studentID);
if( NULL == (p = find_student(studentID) ) )
{
printf("studentName: %s\n", p->studentName);
printf("Marks: %d\n", p->studentGrade);
}
else
{
printf("student not found.\n");
}
} // end function: search
void print(struct phbook *list)
{
struct phbook *p;
printf("Student_Number Student_studentName Student_Mark\n");
for (p = list; p != NULL; p = p->next)
printf("%7d %-25s %d\n", p->studentID, p->studentName, p->studentGrade);
} // end function: print
void saveToFile(struct phbook *list)
{
FILE* fp;
fp = fopen("results.txt", "w");
struct phbook* cur = list; //he
while (cur != NULL)
{
fprintf(fp, "%s\n", list->studentName);
fprintf(fp, "%d\n", cur->studentID);
fprintf(fp, "%d\n", cur->studentGrade);
cur = cur->next;
}
fclose(fp);
} // end function: saveToFile
void readFile( struct phbook* list)
{
FILE* fp = NULL;
if (!(fp = fopen("results.txt", "r")))
{
perror( "fopen for read of results.txt failed");
return;
}
//implied else, fopen successful
char TempstudentName[10];
int TempNumber;
int TempMark;
while (3 == fscanf(fp, " %19s %d %d", TempstudentName, &TempNumber, &TempMark ) )
{
insertFull(list, TempNumber, TempstudentName, TempMark);
}
} // end function; readFile
void insertFull(struct phbook* list,
int studentID,
char studentName[10],
int studentGrade)
{
struct phbook *cur;
struct phbook *prev;
struct phbook *new_node;
if( NULL == (new_node = malloc(sizeof(struct phbook)) ) )
{
perror( "malloc for size of struct phbook failed" );
return;
}
for (cur = list, prev = NULL;
cur != NULL && new_node->studentID > cur->studentID;
prev = cur, cur = cur->next)
{
;
}
new_node->studentID = studentID;
new_node->studentGrade = studentGrade;
strcpy(new_node->studentName, studentName);
new_node->next = cur;
if (!prev)
{
list = new_node;
}
else
{
prev->next = new_node;
}
} // end function: insertFull
I did not add all the necessary error checking, so you will have to do that.
I added the missing prototypes
I corrected several minor coding errors

Resources