dspaces1
dspaces1

Reputation: 193

Comparing 2 substrings in C

I having trouble reading a string of characters from a file and then comparing them for the first part of my homework on ubuntu using C. So the program compiles fine but it seems I get stuck in an infinite loop when it gets to the while loop under the compare string portion of the code. Thanks.

Also, can I get some advice on how to take multiple inputs from the terminal to compare the string from the 'bar' file and the string of x substring of characters after that in the terminal. My output should look like:

% echo "aaab" > bar
% ./p05 bar aa B
2
1
%

This is what I have so far:

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

int main(void /*int argc, char *argv[]*/) 
{

  /******* Open, Read, Close file**********/
  FILE *ReadFile;

  ReadFile = fopen(/*argv[1]*/"bar", "r");

  if(NULL == ReadFile)
    {
      printf("\n file did not open \n");
      return 1;
    }

  fseek(ReadFile, 0 , SEEK_END);  
  int size = ftell(ReadFile); 
  rewind(ReadFile);                

  char *content = calloc( size +1, 1); 

  fread(content,1,size,ReadFile);     

  /*fclose(ReadFile); */                 

  printf("you made it past opening and reading file\n");
  printf("your file size is %i\n",size);

  /*********************************/


  /******String compare and print*****/
  int count =0;
  const char *tmp = "Helololll";
  while (content = strstr(content,"a"))
    {
      count++;
      tmp++;
  }
  printf("Your count is:%i\n",count);

  /***********************************/
    return 0;
}

Upvotes: 0

Views: 148

Answers (1)

D.Shawley
D.Shawley

Reputation: 59583

The following loop is infinite if the character 'a' occurs in content.

while (content = strstr(content, "a"))
{
    count ++;
    tmp ++;
}

It resets content to point to the location of the first occurrence of 'a' on the first iteration. Future iterations will not change the value of content. IOW, content points to "aaab" so the call to strstr will find the first 'a' every time. If you replace tmp++ with content++ inside of your loop, then it will be closer to what you want. I would probably write this with a for loop to make it a little more clear that you are iterating.

char const * const needle = "a";
for (char *haystack=content; haystack=strstr(haystack, needle); haystack++) {
    count++;
}

The haystack is incremented so that it always decreases in size. Eventually, you will not find the needle in the haystack and the loop will terminate.

Upvotes: 1

Related Questions