将文本文件读入结构

我的文本文件是这样的(文件中的数据也可以增加)

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 

我的结构是这样的

  struct input_par { int key_node; char src_ip[15]; char dst_ip[15]; int src_port; int dst_port; }; 

我必须从存储在文件中的数据中填充这个结构,一旦完成输入结构的5个成员我必须将此结构发送到函数,即,我填充结构

  822 172.28.6.56 172.34.34.53 3244 5434 

然后我将这个结构发送到一个函数,在将它发送到函数后,我应该再次输入带有文件中下一个数据的结构,即

  844 192.150.160.145 192.67.45.123 2344 234 

我必须继续这样做直到我到达EOF。 我使用fscanf它不能正常工作怎么做? 请帮助

只要每个结构之间实际上只有一个空间……我可能会做这样的事情。 它非常难看,但只要你知道你的最大线路尺寸肯定并且文件结构没有任何打嗝(额外的空白线等)就可以完成工作。 否则你最好编写更好的代码来处理和中断/返回exception情况。

正如评论所指出的那样,你需要确保增加你的char数组,以便最后考虑’\ n’。 这是对我最初发布的内容的一些修改。 注意,如果行结尾是基于Windows的(我相信),这可能会破坏。 我添加了一点hack来尝试纠正数组空间和\ n字符的问题。

 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 } 

您可以通过一次调用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 }