Reputation: 21
i want to copy this data @822!172.28.6.137!172.28.6.110!5000!6000| form file input_data to this structure,to copy 822 from the file to input.key and 172.28.6.137 to src_ip when ever ! is encountered it should copy the data from file to next member of the structure how to do this?
struct input_par
{
char key[5];
char src_ip[15];
char dst_ip[15];
char src_port[5];
char dst_port[5];
};
main()
{
int i;
char ch;
FILE *fp;
struct input_par input;
fp = fopen("input_data","r");
if(fp == NULL)
printf("file open failed \n");
else
{
ch = fgetc(fp);
if(ch=='@')
printf("data is valid\n");
fseek(fp,1,1);
while(ch!='|')
{
input.key =
input.src_ip =
input.dst_ip =
input.src_port =
input.dst_port =
}
}
Upvotes: 1
Views: 3362
Reputation: 40558
You can use fscanf. I would do something like:
struct input_par {
char key[5];
char src_ip[15], dst_ip[15];
int src_port;
int dst_port;
}
struct input_par ip;
if ( fscanf(fp, "@%s!%s!%s!%d!%d",
ip.key, ip.src_ip, ip.dst_ip, ip.src_port, ip.dst_port) != 5 )
do_error();
Upvotes: 1
Reputation: 11377
A call to fscanf will do the job:
fscanf(fp, "@%[0-9]!%[0-9.]!%[0-9.]!%[0-9]!%[0-9]|", input.key, input.src_ip, input.dst_ip, input.src_port, input.dst_port);
Note that you first have to make sure that the input strings do not overflow your array fields.
Upvotes: 0
Reputation: 1800
First, let's have a function which reads one field(though it won't detect partially read fields)
int read_field(FILE *f,char *destination,size_t max_len)
{
int c;
size_t count = 0;
while(c = fgetc(f)) != EOF) {
if(c == '!' || c == '|')
break;
if(count < max_len - 1)
destination[count++] = c;
}
destination[count] = 0;
return count;
}
Then read the fields:
int ch = fgetc(fp);
if(ch=='@') {
int ok;
printf("data is valid\n");
ok = get_field(fp,input.key,sizeof input.key);
ok && get_field(fp,input.src_ip,sizeof input.src_ip);
ok && get_field(fp,input.dst_ip,sizeof input.dst_ip);
ok && get_field(fp,input.src_port,sizeof input.src_port);
ok && get_field(fp,input.dst_port,sizeof input.dst_port);
if(!ok) {
puts("parse error");
}
}
Upvotes: 0
Reputation: 599
You can use regular expressions see regexp.h from libstd
If you just have to use this kind of thing here, you can juste go through your char[] and count the ! and depending and how much you have previously seen you add the chars you've read in the correct section.
(also fscanf is easier)
Upvotes: 1