Thread: search function failure

  1. #1
    Registered User
    Join Date
    Apr 2010
    Posts
    32

    Unhappy search function failure

    Hi there.

    I have problems with my search function when i read in the command search and then also read in the word that needs to be searched. eg when i enter the command "search blah" it it supposed to search for the word "blah" through the file and then print out the lines which matches the search phrase. Between the search command and the phrase there is a whitespace. Im trying to separate the string so that only the uses the last bit of the search command becuase since i dont want it to also compare it to the "search" when i type it in.

    However it is not working.

    Can some1 plz tell me wats going on and tell me how to fix this.

    Thanks in advance.

    Code:
    int search(char str[][100],char input[],int filelines);
    
    int main(int argc,char*argv[]){
      
      FILE *fp;
      
      int filelines=0;
      
       int i=0;
           
       char str[1000][100];
    
       char input[100];
       
    
      while(!EXIT_SUCCESS){     
    
         i=0;
          
         printf("Enter command > ");
                
         fgets(input,100,stdin);
           
            if(strcmp(input,"print\n") == 0){
    
                     fp=fopen(argv[1],"r");
     / /i have loop here to read in the contents of file.
     
             }
     
            search(str,input,filelines);
     
      }
                     
    return 0;
    
    }
    
    int search(char str[][100],char input[100],int filelines){
    
        char input2[100];
    
        int j=0;
    
        int i=0;
    
       // char *strptr;
    
        char *strptr = &str[0][100]; // this array is where the stuff is when the file was read in in the main function
      
        j=strlen(input2);
    
        input2[j-1]='\0';
    
        if(strcmp(input,"search ") == 0){
       
           fgets(input2,100,stdin);
    
           while((strptr = strstr(strptr,input2)) != NULL){//compares to the stuff in the array where the contents of the file are.
                
                printf(" %s",str[i]);
    
                i++;            
                 
                strptr++;
    
           }
    
         }
    
    return 0;
    
    }
    Last edited by compnub1; 05-21-2010 at 10:54 PM.

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    fgets reads a line up to a \n or until N elements. If you want that line split into words, use sscanf to split it up.


    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Apr 2010
    Posts
    32
    problem is the search term might be more then 1 search term like "search blah blah"

    sscanf stops when there is a space.



  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    It doesn't have to. Read the man page. Besides, you can always just peel off the first word and then treat everything else as the remainder line.


    Quzah.
    Hope is the first step on the road to disappointment.

  5. #5
    Registered User
    Join Date
    Apr 2010
    Posts
    32
    How do you peel of the first word and treat everything else as the remaining line.
    Can some1 plz post an example on how to do it because im at a lost of how to do it. Also Im not sure if my strstr is comparing the the thing i inputed to the stuff in the file.

  6. #6
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    There are lots of ways to do it. You can use a loop and copy characters one at a time to some place else until you hit a space, then copy everything else some place else. You can use a couple of format specifiers and just use sscanf. There are lots of ways to do it. So how about actually trying?


    Quzah.
    Hope is the first step on the road to disappointment.

  7. #7
    Registered User
    Join Date
    Apr 2010
    Posts
    32
    OK I tried using a loop to spilt the strings up but when i type in search and a search phrase nothing happens. I dont understand why this is happening. Could someone plz tell me why because i have been stuck here doing this for serveral hours

    Code:
    int main(int argc,char*argv[]){
      
      FILE *fp;
      
      int filelines=0;
      
       int i=0;
           
       char str[1000][100];
    
       char input[100];
       
    
      while(!EXIT_SUCCESS){     
    
         i=0;
          
         printf("Enter command > ");
                
         fgets(input,100,stdin);
           
            if(strcmp(input,"print\n") == 0){
    
                     fp=fopen(argv[1],"r");
     / /i have loop here to read in the contents of file.
     
             }
     
            search(str,input,filelines);
     
      }
                     
    return 0;
    
    }
    
    int search(char str[][100],char input[100],int filelines){
    
        char input2[100];
    
        char input3[100];
    
        int j=0;
    
        int i=0;
     
        int k;
    
        char *strptr = input3;
       
        j=strlen(input)-1;
    
        input[j]='\0';
    
        for(i=0; input[i] != ' '; i++){
    
           input[i]=input2[i];
    
        }
    
        while(input[j] != ' '){
    
             j--;
    
             k=j;
    
        }
    
        while(input[k]!='\0'){
    
             input[k]=input3[k];
    
             k++;
        }
     
        if((strcmp(input2,"search")) == 0){
    
           while((strptr = strstr(strptr,input3)) != NULL){
    
                printf("%s",str[i]);
    
                i++;
    
                strptr++;
           }
    
        }
    
    return 0;
    
    }

  8. #8
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Code:
    abcdefg abcdefg abcdefg
    0123456^
    You loop until you hit a space.
    Then you need to add a \0 to the array you've copied the word to, so that it makes it an actual string.
    Then you increment your counter to skip that space, and you continue copying until you have copied the \0 to your second string.


    Quzah.
    Hope is the first step on the road to disappointment.

  9. #9
    Registered User
    Join Date
    Apr 2010
    Posts
    32
    Ok i put a null character at the back of char input2 and char input3. I then I used the a loop to get the position by using strlen and then going backwards until it hits the space. I then assign the k to this value and then i use another arrray to copy the remaining stuff starting from that array position. however it still doesnt work.

    Code:
     int main(int argc,char*argv[]){
      
      FILE *fp;
      
      int filelines=0;
      
       int i=0;
           
       char str[1000][100];
    
       char input[100];
       
    
      while(!EXIT_SUCCESS){     
    
         i=0;
          
         printf("Enter command > ");
                
         fgets(input,100,stdin);
           
            if(strcmp(input,"print\n") == 0){
    
                     fp=fopen(argv[1],"r");
     / /i have loop here to read in the contents of file.
     
             }
     
            search(str,input,filelines);
     
      }
                     
    return 0;
    
    }
    
    
    
    int search(char str[][100],char input[100],int filelines){
    
        char input2[100];
    
        char input3[100];
    
        int j=0;
    
        int i=0;
     
        int k;
      
        char *strptr = input3;
       
        j=strlen(input)-1;
    
        input[j]='\0';
    
        for(i=0; input[i] != ' '; i++){
    
           input[i]=input2[i];
           
        }
    
        input2[i]='\0';
        
        while(input[j] != ' '){
    
             j--;
    
             k=j;
    
        }
    
        while(input[k]!='\0'){
    
             input[k]=input3[k];
    
             k++;
        }
    
        input3[k]='\0';
     
        if((strcmp(input2,"search")) == 0){
    
           while((strptr = strstr(strptr,input3)) != NULL){
    
                printf("%s",str[i]);
    
                i++;
    
                strptr++;
           }
    
        }
    
    return 0;
    
    }

  10. #10
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    I think strtok is maybe a good thing to use here.

    Code:
    #include <stdio.h>
    #include <string.h>
    
    void for_example (char *string) {
    	char *tok = strtok(string," ");
    	while (tok) {
    		printf("->%s<-\n", tok);
    		tok = strtok(NULL," ");
    	}
    }
    
    
    int main(int argc, const char *argv[]) {
    	char input[4096] = {0};
    	int i;
    
    	if (argc < 2) {
    		puts("No arg!");
    		return -1;
    	}
    
    	for (i=1;i<argc;i++) {
    		strcat(input,argv[i]);
    		input[strlen(input)] = ' ';
    	}
    
    	for_example(input);
    
    	return 0;
    }
    You can compile this and then run it from the command line adding whatever string you are want to deal with, eg:

    [root/media/sda6/root/C] ./a.out search and this
    ->search<-
    ->and<-
    ->this<-


    I would copy the items into an array of strings and then use those line by line when searching the file -- than is, search each line once for each term rather than read the file once for each term. Your existing code is a little odd, lemme post that separately.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  11. #11
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Code:
    int search(char str[][100],char input[100],int filelines){
    It's not necessary to use "char input[100]", use "char *input". It's the same anyway (you cannot pass the value of a whole array, you can just pass a pointer).
    Code:
        char input2[100];
        char input3[100];
        int j=0;
        int i=0;
        int k;
      
        char *strptr = input3;
       
        j=strlen(input)-1;
        input[j]='\0';
    Why do you do this?

    Code:
        for(i=0; input[i] != ' '; i++){
           input[i]=input2[i];
    These are backward.

    Code:
       
        while(input[j] != ' '){
             j--;
             k=j;
        }
    
        while(input[k]!='\0'){
             input[k]=input3[k];
    Backward again! Also this whole section is very torturous...why do you want to work thru the string from both ends?
    Code:
     
        if((strcmp(input2,"search")) == 0){
           while((strptr = strstr(strptr,input3)) != NULL){
                printf("%s",str[i]);
    I don't understand the purpose of str[][] so am lost at this point -- are those the lines from the file?
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  12. #12
    Registered User
    Join Date
    Apr 2010
    Posts
    32
    str[][] is the array where i store the lines of data from a sample file.

    Then i run the program like this ./program text1.txt

    and then my function is supposed to search for words in the file.

    eg. i type in "search blah" and then it searchs the phrase blah and then if it matches it prints that line out. Thats y i have loops separting to seperate the string into two bits like "search" and "blah. I then only want to compare blah through the str[][] array where the informationed is stored.

  13. #13
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Okay, this is what I meant earlier. It's a development of the function from the last post:
    Code:
    void for_example (char *string) {
    	char *tok = strtok(string," "),
    		array[10][32], buffer[1024];
    	int c = 0, i;
    	FILE *in = fopen("test.c","r");
    
    /* populate "array" */
    	while (tok) {
    		printf("->%s<-\n", tok);
    		if (strcmp(tok,"search") == 0) {
    			tok = strtok(NULL," ");
    			continue;
    		}
    		strcpy(array[c++],tok);
    		if (c==10) break;	// max terms
    		tok = strtok(NULL," ");
    	}
    
    /* scan file */
    	while (fgets(buffer,1024,in)) {
    		for (i=0; i<c ;i++) {
    			if (strstr(buffer,array[i])) {
    				printf("%s",buffer);
    				break;	// don't reprint lines
    			}
    		}
    	}
    	fclose(in);
    }
    "test.c" is the source code itself, and the rest is the same as before. So when I run this:

    ./a.out search str tok arg

    I get:
    Code:
    ->search<-
    ->str<-
    ->tok<-
    ->arg<-
    #include <string.h>
    void for_example (char *string) {
    	char *tok = strtok(string," "),
    	while (tok) {
    		printf("->%s<-\n", tok);
    		if (strcmp(tok,"search") == 0) {
    			tok = strtok(NULL," ");
    		strcpy(array[c++],tok);
    		tok = strtok(NULL," ");
    			if (strstr(buffer,array[i])) {
    int main(int argc, const char *argv[]) {
    	if (argc < 2) {
    		puts("No arg!");
    	for (i=1;i<argc;i++) {
    		strcat(input,argv[i]);
    		input[strlen(input)] = ' ';
    Only the lines with "str", "tok", or "arg" in them The only problem with this is you can't search for "search".
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  14. #14
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    Code:
      while(!EXIT_SUCCESS){
    If I'm not wrong, standard gives no grantee that EXIT_SUCCESS to be zero.

  15. #15
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    It doesn't really matter what it's guaranteed to be, since he's just comparing to a constant--his loop condition never changes.


    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compiling sample DarkGDK Program
    By Phyxashun in forum Game Programming
    Replies: 6
    Last Post: 01-27-2009, 03:07 AM
  2. Attempt to write function search()
    By elsewhere in forum C Programming
    Replies: 6
    Last Post: 12-03-2008, 08:18 AM
  3. <Gulp>
    By kryptkat in forum Windows Programming
    Replies: 7
    Last Post: 01-14-2006, 01:03 PM
  4. Bisection Method function value at root incorrect
    By mr_glass in forum C Programming
    Replies: 3
    Last Post: 11-10-2005, 09:10 AM
  5. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 10:03 AM