I have this csv file:
NAME, NUMBER, ADDRESS, EMAIL
Kevin, +62 812-xxx-xxx, Jln.Anggrek Merah 3, [email protected]
Adwi, +62 821-xxxx-xxxx, Jln.Ruhui Rahayu, [email protected]
Wasis, +62 813-xxxx-xxxx, Jln.Pramuka 6 25, [email protected]
Alief, +62 811-xxxx-xxx, Jln.Padat Karya, [email protected]
This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 50
typedef struct Contact
{
char name[MAX];
char number[MAX];
char address[MAX];
char email[MAX];
struct Contact *next;
}
Contact;
void create_linkedList(Contact **start, Contact p)
{
Contact *new = malloc(sizeof(Contact));
strcpy(new->name, p.name);
strcpy(new->number, p.number);
strcpy(new->address, p.address);
strcpy(new->email, p.email);
new->next = *start;
*start = new;
}
void printList(Contact *start)
{
Contact *cursor = start;
while (cursor != NULL)
{
printf("%s\n", cursor->name);
cursor = cursor->next;
}
}
void sorting(Contact *start)
{
Contact *cursor = start, *traverse = NULL;
Contact *tmp, *tmp_next;
while (cursor != NULL)
{
traverse = cursor;
while (traverse->next != NULL)
{
if (strcasecmp(traverse->name, traverse->next->name) > 0)
{
tmp = traverse;
tmp_next = traverse->next->next;
traverse->next = tmp;
traverse->next->next = tmp_next;
}
traverse = traverse->next;
}
printf("Prepare!\n");
cursor = cursor->next;
}
}
int main(void)
{
FILE *file = fopen("contacts.csv", "r");
if (file == NULL)
return 1;
Contact person;
Contact *start = NULL;
// Loop inside csv file til' the end of file
while(fscanf(file, "%[^,], %[^,], %[^,], %[^\n] ", person.name, person.number, person.address, person.email) == 4)
{
# Skip header file from csv
if (strcmp("NAME", person.name) == 0)
continue;
create_linkedList(&start, person);
}
printList(start);
// Swapped
sorting(start);
printList(start);
return 0;
}
So, after i successfully created a linked list that connect each person data in my csv file, i want to sort it by their name and then print it. But if you compile my code, it causes segmentation fault.
In my sort() function i try to change the node (next) of each person. Because i think if i only swap the value of each element, the node (next) will still point same person as before. So i was thinking maybe i can only swap the node (next).
I can do it if it's only sorting value in an array. But linked list it's difficult for me as beginner.
Can you help me, please? Maybe write me some new code and explain the solution, if you guys have it. Thanks!