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.
Related
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
struct Node {
/* Data fields with appropraiate types */
char fname[64];
char lname[64];
char puid[16];
int Age;
struct Node *next;
};
struct List {
struct Node *start;
int numNodes;
};
struct List * initialize_list() {
struct List *list = (struct List *) malloc(sizeof(struct List *));
list -> numNodes = 0;
list -> start = (struct Node *) malloc(sizeof (struct Node *));
return list;
}
struct List * CreateList() {
struct List *list = initialize_list();
return list;
}
void Traverse(struct List *list) {
struct Node *node = (struct Node *) malloc (sizeof(struct Node));
int i = 1;
node = list -> start -> next;
while (node != NULL) {
printf ("\nNode: %d", i);
printf("\nPUID: %s", node -> puid);
node = node -> next;
i++;
}
if (i == 1) {
printf("\n\nEmpty List");
}
}
struct Node *CreateNode(char first_name[], char last_name[], char PUID[], int age) {
struct Node *newNode = (struct Node *) malloc (sizeof(struct Node *));
strcpy(newNode->fname, first_name);
strcpy(newNode->lname, last_name);
strcpy(newNode->puid, PUID);
newNode->Age = age;
newNode->next = NULL;
return newNode;
}
void InsertFront(struct List *list, char first_name[], char last_name[], char PUID[], int age) {
struct Node *newNode = CreateNode (first_name, last_name, PUID, age);
if (list -> numNodes == 0) {
list -> start -> next = newNode;
list -> numNodes++;
return;
}
newNode -> next = list -> start -> next;
list -> start -> next = newNode -> next;
list -> numNodes++;
return;
}
int main () {
struct List *myList = CreateList();
while (1) {
int option = 0;
char fname[64];
char lname[64];
char puid[16];
int age;
printf("\n0. Exit Program \n1. Insert Front\n2. Insert Middle\n3. Insert End\n4. Delete Front\n5. Delete Middle\n6. Delete End\n7. Traverse \n8. Look Up by Index\n");
printf ("Enter option: ");
option = getchar();
if (option == '0') {
exit (0);
}
else if (option == '1' || option == '2' || option == '3') {
printf("Enter first name: ");
scanf("%s", fname);
printf("Enter last name: ");
scanf("%s", lname);
printf("Enter PUID: ");
scanf("%s", puid);
printf("Enter age: ");
scanf("%d", &age);
if (option == '1') {
InsertFront (myList, fname, lname, puid, age);
}
else if (option == '2') {
int index;
printf ("Enter position to Insert: ");
scanf ("%d", &index);
InsertMiddle (myList, index, fname, lname, puid, age);
}
else if (option == '3') {
InsertEnd (myList, fname, lname, puid, age);
}
}
else if (option == 4) {
}
else if (option == 5) {
}
else if (option == 6) {
}
else if (option == '7') {
Traverse (myList);
}
else if (option == 8) {
}
else {
}
getchar();
}
return 0;
}
I'm relearning some of this but I'm not sure where I'm going wrong.
I get a segmentation fault when the program reaches the Traverse() function.
I can access the Node that before the iteration of the while loop is not complete. As soon as the next iteration begins the myList -> start -> next can't be accessed any longer.
In Create node method:
malloc (sizeof(struct Node *))
Will allocate only 4 or 8 bytes because it sizeof pointer.
It should be:
malloc (sizeof( Node ))
to allocate space for an object
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.
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
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
I am trying to read in a text file in a linked list and successfully displaying it. But I keep getting the "List is Empty" message which corresponds to (head==NULL) while I can successfully get to read and print in the file once by using the puts(id->...) argument in the read function but I cant get to the display function as I mentioned above.
struct node
{
char name[50];
int id;
struct node *next;
} *head;
int main()
{
int i,num;
struct node *r;
head=NULL;
readfile(*r);
while (1)
{
printf("\nList Operations\n");
printf("============\n");
printf("1.Insert\n");
printf("2.Display\n");
printf("3.Delete by ID\n");
printf("4.Delete by Name\n");
printf("5.Exit\n");
printf("Enter your choice: ");
if (scanf("%d", &i) <= 0){
printf("Enter only an integer\n");
exit(0);
} else {
switch(i)
{
case 1:
if(head==NULL)
{
printf("List is Empty\n");
}
else
{
printf("Element in the list are: ");
}
display(r);
break;
case 2:
return 0;
default:
printf("Invalid Choice\n");
}
}
}
void readfile(struct node *r)
{
r=head;
char str[50];
int id;
FILE *ifp=fopen("One.txt","r");
while (fgets(str,50,ifp)!=NULL){
r =(struct node *)malloc(sizeof(struct node));
char *token=strtok(str,",");
strcpy(r->name,token);
puts(r->name);
token=strtok(NULL,"\n");
r->id=token;
puts(r->id);
r->next=NULL;
r=r->next;
}
}
void display(struct node *r)
{
r = head;
if(r == NULL)
{
return;
}
while(r != NULL)
{
printf("Student %s has id %d.\n", r->name,r->id);
r = r->next;
}
printf("\n");
}
In the code you provided you are never assign or allocating anything to head. I guess you need to add code below somewhere
if (head == NULL) {
head = r;
}
or
if (head == NULL) {
head = (struct node *)malloc(sizeof(struct node));
// and initialize it with something
}
Also I recommend you to create more general functions like add_node, like this
void add_node( struct node *r ) {
if(head == NULL) {
head = r;
} else {
struct node* n = head;
while(n->next != NULL) { // go to the end of the list
}
r->next = NULL; // to be sure this will be end of list
n->next = r;
}
}
Then in readfile read data, create new node and pass it to add_node.