读取文本文件到一个结构 [英] reading a text file into a structure

查看:228
本文介绍了读取文本文件到一个结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

和我的结构是这样的。

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

我必须从存储在文件中的数据填补这个结构,具有较好一旦完成输入5承包商,客人的结构的我有这种结构发送到功能
即,我填补结构

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

我要继续这样做,直到我到达EOF。
我用的fscanf它不能正常工作如何做到这一点?请帮助

I have to keep doing this till i reach EOF. I used fscanf it is not working properly how to do this? pls help

推荐答案

您可以阅读一次调用整个结构FSCANF

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
}

这篇关于读取文本文件到一个结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆