Hi,

My code reads a string from a file. But it misses the lastone. can you help me?

1..Text File

102.15.12.10
15.14.106.6
1591
1592
bit_torrent

2.. Code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct list_node{

	char src_ip[15];
	char dst_ip[15];
	char src_port[4];
	char dst_port[4];
	char protocol[15];


};
typedef struct list_node node;





int main(int argc, char *argv[])
{
  FILE *fp;
  node anode;

  int i=0;



  if((fp = fopen(argv[ 1 ], "r"))==NULL) {
    printf("Cannot open file.\n");
    exit(1);
  }

  /*while(!feof(fp)) {
    if(fgets(anode.src_ip, 15, fp))
        printf("%s", anode.src_ip);


  }*/

  bzero(&anode,sizeof(anode));

  fgets(anode.src_ip, 15, fp);
  anode.src_ip[strlen(anode.src_ip)]='\0';
  printf("%s", anode.src_ip);

  fgets(anode.dst_ip, 15, fp);
  anode.dst_ip[strlen(anode.dst_ip)]='\0';
  printf("%s", anode.dst_ip);

  fgets(anode.src_port, 4, fp);
  anode.src_port[strlen(anode.src_port)]='\0';
  printf("%s", anode.src_port);

  fgets(anode.dst_port, 4, fp);
  anode.dst_port[strlen(anode.dst_port)]='\0';
  printf("%s", anode.dst_port);

  fgets(anode.protocol, 11, fp);
  anode.protocol[strlen(anode.protocol)]='\0';
  printf("%s", anode.protocol);

  fclose(fp);

  return 0;
}

It misses "bit_torrent" . Thanks in advance for the help.

> char src_port[4];
This isn't long enough to store "1591\n\0" in the first instance of calling fgets().

It isn't even long enough to store "1591\0"

This article has been dead for over six months. Start a new discussion instead.