I have created a linked list which stores data from file. However I got stuck when I try to print the contents of Linked List. The code is below
1.Text File
102.15.12.10
15.14.106.6
1591
1592
bit_torrent
102.15.12.10
15.14.106.6
1591
1592
bit_torrent
102.15.12.10
15.14.106.6
1591
1592
bit_torrent
102.15.12.10
15.14.106.6
1591
1592
bit_torrent
2.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct list_node{
char src_ip[18];
char dst_ip[18];
char src_port[8];
char dst_port[8];
char protocol[18];
struct list_node *next;
};
struct list_node showdata();
struct list_node* buildlist(struct list_node anode,struct list_node *head);
void print(struct list_node *firstnode);
int main()
{
struct list_node *head;
head=malloc(sizeof(struct list_node));
print(buildlist(showdata(),head));
print(buildlist(showdata(),head));
return 0;
}
struct list_node showdata(){
struct list_node anode;
FILE *fp;
if((fp = fopen("pkt_file.txt", "r"))==NULL) {
printf("Cannot open file.\n");
exit(1);
}
fgets(anode.src_ip, 18, fp);
anode.src_ip[strlen(anode.src_ip)]='\0';
// printf("%s", anode.src_ip);
fgets(anode.dst_ip, 18, fp);
anode.dst_ip[strlen(anode.dst_ip)]='\0';
//printf("%s", anode.dst_ip);
fgets(anode.src_port, 8, fp);
anode.src_port[strlen(anode.src_port)]='\0';
// printf("%s", anode.src_port);
fgets(anode.dst_port, 8, fp);
anode.dst_port[strlen(anode.dst_port)]='\0';
// printf("%s", anode.dst_port);
fgets(anode.protocol, 18, fp);
anode.protocol[strlen(anode.protocol)]='\0';
// printf("%s\n", anode.protocol);
return (anode);
fclose(fp);
}
struct list_node* buildlist(struct list_node anode, struct list_node *head){
struct list_node *current=NULL;
current=malloc(sizeof(struct list_node));
head=malloc(sizeof(struct list_node));
current=head;
if(current==NULL){
head=current=&anode;
printf("1--working\n");
return head;
}
else if(current->next==NULL){
current->next=&anode;
head=current;
printf("2--working\n");
return head;
}
else{
while(current->next!=NULL){
current=current->next;
}
current->next=&anode;
printf("working\n");
return head;
}
}
void print(struct list_node *firstnode){
//firstnode=malloc(sizeof(struct list_node));
if(firstnode->next==NULL){
printf("The node is:%s\n",firstnode->dst_port);
//firstnode=firstnode->next;
}
else{
while(firstnode){
printf("The node is:%s\n",firstnode->dst_port);
firstnode=firstnode->next;
}
}
}
Thanks in advance for help