Hi,
I am using the below program to parse a file ,extarct values and store them into an array.
Here i have same values repeated for example IP , so i need to take only instance of it but rest of data store accordingly.
so the correct format is {IP = 192.168.0.1 , DLD = 123451 , ULD = 123454} .. so on.
The contents of my file ( test_ud.txt ) are as follows.
IP:192.168.0.1 DLD:123451
IP:192.168.0.2 DLD:123452
IP:192.168.0.3 DLD:123453
IP:192.168.0.1 ULD:123454
IP:192.168.0.2 ULD:123455
IP:192.168.0.3 ULD:123456 /*No new line after last entry*/
I just want to find out is there any other efficient way to do this using shell script or a c program.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct data_info {
char ipaddr[20];
char upload_data[20];
char download_data[20];
};
struct data_info *df;
void print( void);
int NOE;
int main( void )
{
FILE *fp;
char str[100];
char *tok,*ip,*dd,*ud;
int noe=0;
fp = fopen("test_ud.txt", "r");
while(fgets(str,sizeof (str),fp)){
noe++;
}
NOE = noe / 2;
printf("NOE = %d\n", NOE);
fseek(fp,0,SEEK_SET);
if(fp){
int cnt = 0;
int i;
int skip_dd = 0;
while(fgets(str,sizeof (str),fp)){
cnt++;
if( cnt == 1 ){
tok = strtok(str,":");
printf("tok = %s\n",ip=strtok(NULL," "));
df=(struct data_info*)malloc(sizeof(struct data_info));
memset(df,0,sizeof(struct data_info));
strcpy(df->ipaddr,ip);
tok = strtok(NULL,":");
printf("tok = %s\n",dd=strtok(NULL,"\n"));
strcpy(df->download_data ,dd);
}else {
i=0;
tok=strtok(str,":");
printf("tok = %s\n",ip=strtok(NULL," "));
tok=strtok(NULL,":");
printf("tok = %s\n",dd=strtok(NULL,"\n"));
while( i< (cnt-1) ){
if (!strcmp(df[i].ipaddr,ip)){
strcpy(df[i].upload_data,dd);
skip_dd = 1;
break;
}
printf(" df[%d].ipaddr = %s\n", i, df->ipaddr);
i++;
}
if(!skip_dd) {
struct data_info* tmp;
tmp = (struct data_info*)realloc(df,sizeof(struct data_info)*cnt);
if(tmp){
df = tmp;
strcpy(df[cnt-1].ipaddr,ip);
strcpy(df[cnt-1].download_data,dd);
} else {
printf("Cannot reallocate\n");
return 0;
}
}
}
printf("\n");
}
}else {
return 0;
}
fclose(fp);
print();
return 0;
}
void print(void )
{
int i=0;
while(i<NOE){
printf("ip = %s dd = %s up = %s\n", df[i].ipaddr,df[i].download_data,df[i].upload_data);
i++;
}
}