-1

I am trying to use strstr to search for any matches using a substring and comparing it to a line of text but haven't been successful in getting a match so far. I am opening and reading a file using popen while trying to do a search with only the ipv4 address looking for matches. What is wrong with my code? Any help will be much appreciated, thanks.

char *buffe = malloc(sizeof(char));

        FILE *rib_file = popen("bgpdump -Mv rib.20160101.0000.bz2", "r");
        while(fgets(buffe, sizeof(buffe), rib_file)!=NULL) {
            if(buffe[strlen(buffe)-1] == '\n')
                buffe[strlen(buffe)-1] = '\0';
          for (int i = 0; i < argc; i++) {
            if((strstr(buffe, argv[i])) != NULL) {
                printf("A match found on line: %d\n", line_num);
                printf("\n%s\n", buffe);

                find_result++;
            }
                line_num++;
          }

        }
            if(find_result == 0) {
                printf("\nSorry, couldn't find a match.\n");
            }

        if (rib_file) {
            pclose(rib_file);
        }

        free(buffe);
    }

an example of what buffe is like:

TABLE_DUMP2|01/01/16 00:00:38|B|202.232.0.3|2497|223.255.254.0/24|2497 7473 3758 55415|IGP

I am trying to print the exact line as above when my code finds a match.

FrankS101
  • 2,112
  • 6
  • 26
  • 40
user1610834
  • 115
  • 2
  • 13
  • We need to know things like what `buffe` is, what you're expecting this code to output, what the code does output, what input you're feeding it, and so on. – David Schwartz Mar 08 '16 at 08:12
  • 3
    You don't show the whole code, but `buffe` seems to be a pointer to allocated memory, because you `free` it later. That means that `sizeof(buffe)` is smaller than you think: It's the size of a pointer, not the number of bytes allocated. – M Oehm Mar 08 '16 at 08:12
  • What is the content of the file, if it is binary data strstr is not the function to use – Mindaugas Mar 08 '16 at 08:13
  • And besides the above, remember that all string functions are case sensitive. – Some programmer dude Mar 08 '16 at 08:14
  • You allocate 1 byte and read in `sizeof(char*)` bytes. That leads to UB. – Spikatrix Mar 08 '16 at 08:35
  • How do you plan to read your file into a 1-byte memory block – M.M Mar 08 '16 at 09:20
  • @Lundin that would be the right code for removing the newline appended by fgets, if earlier problems in the code were fixed (and a zero length check added) – M.M Mar 08 '16 at 09:36

1 Answers1

2

The sizeof function tells you the size of a type. Since buffe is a pointer, your call to sizeof(buffe) will get you the size of a pointer on your platform which is almost certainly not what you want. Did you mean to pass fgets the size of the thing buffe points to?

David Schwartz
  • 179,497
  • 17
  • 214
  • 278