3MIN3M
3MIN3M

Reputation: 67

Error while using fgets in C

I'm writing a small program to check how the function strcasestr works.

What the code below does:

  1. Asks the user to enter a line of text.
    Example first input: blah bla blah blah the Word we are looking for. Example second input: Word

  2. What the program should print is: Word we are looking for.

  3. But it gives me a Segmentation fault (core dumped) error.

I suspect I'm using fgets() incorrectly. When I run the program using scanf to read the input (of course entering the first input withoutspaces) it works and gives me the expected output.

Any idea what's causing the segmentation fault error? How to correct this?

#define _GNU_SOURCE
#define max_buff 1000
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
char *answer;
//char * strcasestr (const char *haystack, const char *needle);

void strip_crlf(char* s);

void strip_crlf(char* s)
{
    char* p = strpbrk(s, "\r\n");
    if (p) *p = '\0';
}

int main(){
  char fname[max_buff+1];
  char lname[max_buff+1];

  printf("Enter the line of text you are searching for ");
  //scanf("%s", fname);

  fgets(fname,max_buff,stdin);
  //printf("%s",fname);
  strip_crlf(fname);

  printf("Enter the search term ");
  //scanf("%s", lname);
  fgets(lname,max_buff,stdin);
  strip_crlf(lname);
  //printf("%s",lname);
  if((answer=strcasestr(fname,lname))!=NULL){

  // printf("now we have something in answer ");
    printf("%s\n",answer);
  }
  else
      printf(" strcasestr failed\n");

}

EDITED: to reflect suggestions made in comments/answers below. the program now prints:

 strcasestr failed

...Ughh.

Edit2: program works now. thanks for all your help everyone!

Upvotes: 0

Views: 164

Answers (2)

goji
goji

Reputation: 7132

You're not checking for a failure from strcasestr(), which IS failing, because you're not stripping \n or \r\n from your inputs.

The only search that will succeed is if it matches the end of the first input.

To strip CRLF:

void strip_crlf(char* s)
{
    char* p = strpbrk(s, "\r\n");
    if (p) *p = '\0';
}

Then just strip_crlf(fname); after fgets. Same for lname.

Upvotes: 2

Barmar
Barmar

Reputation: 782499

You need to check if the comparison succeeded before trying to print the result:

if (answer) {
    printf("%s\n", answer);
} else {
    printf("No match\n");
}

The reason the comparison is failing is probably because fgets() includes the newline in the buffer, but scanf() doesn't. You'll need to remove the newline at the end of the string if you don't want it to mess up the comparison.

Upvotes: 2

Related Questions