reading a text file into a structure
my text file is like this (the data in the file can also increase)
开发者_开发技巧 822
172.28.6.56
172.34.34.53
3244
5434
844
192.150.160.145
192.67.45.123
2344
234
700
192.13.56.6
192.89.95.3
4356
3566
522
172.28.6.137
172.28.6.110
2543
5245
900
255.255.255.255
244.244.244.244
2435
3245
and my structure is like this
struct input_par
{
int key_node;
char src_ip[15];
char dst_ip[15];
int src_port;
int dst_port;
};
i have to fill this struture from data stored in file, once it completes inputting the 5 memebers of the structure i have to send this structure to a function i.e, i fill the structure with
822
172.28.6.56
172.34.34.53
3244
5434
then i send this structure to a function, after sending it to a function i should again input the structure with the next data in the file i.e
844
192.150.160.145
192.67.45.123
2344
234
I have to keep doing this till i reach EOF. I used fscanf it is not working properly how to do this? pls help
As long as there is actually just one space between each of these structures... I might do something like this. It's pretty ugly, but would get the job done as long as you know your max line size for sure and the file structure doesn't have any hiccups (extra blank lines, etc). Otherwise you'd be better off writing much better code that handles and breaks/returns in case of exceptions.
As the comments note, you'll want to make sure to increase your char array's to account for the '\n' at the end. Here's some modifications to what I originally posted. Note, this may break if the line endings are Windows based (I believe). I added a little hack to try to correct the issue of array space and \n characters.
struct input_par
{
int key_node;
char src_ip[21];
char dst_ip[21];
int src_port;
int dst_port;
};
FILE* file = fopen("inputfile.txt", "r");
char linebuffer[21]; //a little extra room here than needed, presumably...
struct input_par ip;
int i = 0, l = 0;
while(fgets(linebuffer, 20, file))
{
ip.key_node = atoi(linebuffer);
fgets(linebuffer, 20, file);
strcpy(ip.src_ip, linebuffer);
l = strlen(linebuffer);
for(i = 0; i < l; ++i){
if(linebuffer[i] == '\n'){
linebuffer[i] = '\0'
break;
}
}
fgets(linebuffer, 20, file);
strcpy(ip.dest_ip, linebuffer);
l = strlen(linebuffer);
for(i = 0; i < l; ++i){
if(linebuffer[i] == '\n'){
linebuffer[i] = '\0'
break;
}
}
fgets(linebuffer, 20, file);
ip.src_port = atoi(linebuffer);
fgets(linebuffer, 20, file);
ip.dst_port = atoi(linebuffer);
fgets(linebuffer, 20, file); //get the empty line
}
You can read the entire structure in one call to fscanf
--->
while(!feof(fp))
{
input_par ip;
int ret = fscanf(fp,"%*[ \t\n]%d%*[ \t\n]%s%*[ \t\n]%s%*[ \t\n]%d%*[ \t\n]%d",&ip.key_node,&ip.src_ip,&ip.dst_ip,&ip.src_port,&ip.dst_port);
if (ret !=5)
{
//skip this record
continue;
}
//process record ip
}
精彩评论