开发者

segmentation fault while using fread and not able to read the data from the file

Here want to copy the data from the file enter_data and pass it to the function insert(key,keys) but i get a segmentation fault and more over i am not able to read the data from the file

here classifier is a structure, and packet_filter has structure of ip and udp in that i want to enter src and dst ip adddress and src and dst port number

    struct classifier
    {
        int key_node;
        struct packet_filter pktFltr;
        struct classifier *next;
    }__attribute__((packed));




    void addrule(struct classifier keys)
    {
            int key;
            FILE *fp;
            fp = fopen("enter_data","r");
            fread(&keys, sizeof (struct classifier), 3, fp);
            insert(key,keys);
            fclose(fp);
    }

                    file: enter_data

        key = 822;
        keys.key_node = 822;
        inet_aton("172.28.6.137", &(keys.pktFltr.ip.ip_src));
        inet_aton("172.28.6.10",&(keys.pktFltr.ip.ip_dst));
        keys.pktFltr.protocol.proto.uh_sport = ntohs(1032);
        keys.pktFltr.protocol.proto.uh_dport = ntohs(5000);
        keys.next = NULL;


        key = 522 ;
        keys.key_node = 522;
        inet_aton("172.28.6.87", &(keys.pktFltr.ip.ip_src));
        inet_aton("172.28.6.110",&(keys.pktFltr.ip.ip_dst));
        keys.pktFltr.protocol.proto.uh_sport = ntohs(1032);
        keys.pktFltr.protocol.proto.uh_dport = ntohs(5010);
        keys.next = NULL;

        key = 522 ;
        keys.key_node = 522;
        inet_aton("172.28.6.87", &(keys.pktFltr.ip.ip_sr开发者_Python百科c));
        inet_aton("172.28.6.110",&(keys.pktFltr.ip.ip_dst));
        keys.pktFltr.protocol.proto.uh_sport = ntohs(1032);
        keys.pktFltr.protocol.proto.uh_dport = ntohs(5011);
        keys.next = NULL;


This will not work, because you try to read binary file, while your file is text.

Second - you need to check if fp is NULL after trying to open the file - just an advice.

Third - even if the file was binary, this wouldn't work, as

fread(&keys, sizeof (struct classifier), 3, fp);

should be

//                                      vvv
fread(&keys, sizeof (struct classifier), 1, fp);

As keys is not an array and you need to read just on block.


You seem to not allocate enough room for your 3 keys.

void addrule(struct classifier keys)
{
....
    fread(&keys, sizeof (struct classifier), 3, fp);    // Here you read 3 keys and put into &keys, but you gave only one struct to your method

Maybe with a loop reading one key at each :

void addrule(struct classifier keys)
{
....
    while fread(&keys, sizeof (struct classifier), 1, fp)
    {
        insert(key,keys);
    }
    fclose(fp);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜