Hi,
I am stuck in file reading problem. I have tried various solutions but nothing worked. Actually I can't develop a logic to do so. I want to read some lines from file and pass them to structure. When reading a file you must use WHILE loop. I am posting my code and file here. I want to read from 10.10.10.1 to eDonkey and assign these values to a structure. Then start reading from the next one 10.10.10.3 to Bittorrent and so on and also adjust it to a structure. Can anyone help me in this regard.
1. TEXT FILE
10.10.10.1
10.10.10.2
1696
1697
eDonkey
10.10.10.3
10.10.10.4
1698
1699
Bittorrent
10.10.10.5
10.10.10.6
1700
1701
gnutella
10.10.10.7
10.10.10.8
1701
1702
eDonkey
10.10.10.9
10.10.10.10
1703
1704
gnutella
2.CODE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct file_data{
char src_ip[18];
char dst_ip[18];
char src_port[8];
char dst_port[8];
char p2p_proto[18];
struct file_data *next;
};
typedef struct file_data data;
data *start_node=NULL;
data readdata();
void buildlist(data);
int main(){
int i=0;
for(i=0;i<5;i++){
buildlist(readdata());
}
printf("The program is working\n");
return 0;
}
data readdata(){
data getdata;
FILE *fp;
char input[18];
int i=0;
//getdata=(data *)malloc(sizeof(data));
fp=fopen("pktfile.txt","r");
while(fgets(input,18,fp)!=NULL){
if(i==0){
strcpy(getdata.src_ip, input);
//printf("%s",getdata.src_ip);
i++;
}
else if(i==1){
strcpy(getdata.dst_ip, input);
//printf("%s",getdata.dst_ip);
i++;
}
else if(i==2){
strcpy(getdata.src_port, input);
//printf("%s",getdata.src_port);
i++;
}
else if(i==3){
strcpy(getdata.dst_port, input);
//printf("%s",getdata.dst_port);
i++;
}
else if(i==4){
strcpy(getdata.p2p_proto, input);
//printf("%s",getdata.p2p_proto);
i=0;
getdata.next=NULL;
return (getdata);
bzero(&getdata,sizeof(getdata));
}
/*else{
printf("Wrong File");
break;
}*/
//printf("%s",input);
}
fclose(fp);
}
void buildlist(data node){
data *traverse;
start_node=(data *)malloc(sizeof(data));
//node=(data *)malloc(sizeof(data));
traverse=(data *)malloc(sizeof(data));
if(start_node==NULL){
start_node=node;
}
else if(start_node->next==NULL){
start_node->next=node;
traverse=start_node;
}
else{
traverse=start_node;
while(traverse->next!=NULL)
traverse=traverse->next;
}
traverse->next=node;
}
}
Thanks in advance