search a string in text file in C

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • agsrinivasan
    New Member
    • Feb 2007
    • 15

    search a string in text file in C

    hi everyone,
    i have to search a one word in txt file using C program,..I tried but output not comming right...please give me a flow for that...


    i am newbie to C...


    regards....

    srini
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    Originally posted by agsrinivasan
    hi everyone,
    i have to search a one word in txt file using C program,..I tried but output not comming right...please give me a flow for that...


    i am newbie to C...


    regards....

    srini
    Let's see the code you've written.

    Comment

    • agsrinivasan
      New Member
      • Feb 2007
      • 15

      #3
      Originally posted by r035198x
      Let's see the code you've written.
      i have read all datas into one buffer....from that I have to search the word...

      see my code....

      Code:
      #include <stdio.h>
      #include <stdlib.h>
      #include<string.h>
      
      int main () {
        FILE * pFile;
        long lSize;
        char * buffer;
        size_t result;
      
        pFile = fopen ( "/home/srinivas/Desktop/cl.txt" , "r+" );
        if (pFile==NULL) {fputs ("File error",stderr); exit (1);}
      
        // obtain file size:
        fseek (pFile , 0 , SEEK_SET);
        lSize = ftell (pFile); printf(" The file size is = %ld",lSize);
        rewind (pFile);
      
        // allocate memory to contain the whole file:
        buffer = (char*) malloc (sizeof(char)*lSize);
        if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
      
        // copy the file into the buffer:
        result = fread (buffer,1,lSize,pFile);
           
        puts(buffer);
        if (result != lSize) {fputs ("Reading error",stderr); exit (3);}
      
      fclose (pFile);
        free (buffer);
        return 0;
      }
      Last edited by agsrinivasan; Feb 12 '07, 05:17 PM. Reason: to change a file

      Comment

      • narasip
        New Member
        • Feb 2007
        • 1

        #4
        Hi Srini,

        From the code I see that ftell(pFile) will point to the beginning of the file and hence its ouput is 0. This is because you have used SEEK_SET in the fseek func which will bring you to the begining of the file. Try changing SEEK_SET to SEEK_END in the fseek call in the code which moves the cursor to the end of your file. now ftell(pfile) will give you the cursor value which will print the output.

        Hope the following code works for you.

        Code:
        #include <stdio.h>
        #include <stdlib.h>
        #include<string.h>
        
        int main () {
          FILE * pFile;
          long lSize;
          char * buffer;
          size_t result;
        
          pFile = fopen ( "/mydir2/narasip/zippy.c" , "r+" );
          if (pFile==NULL) {fputs ("File error",stderr); exit (1);}
        
          fseek (pFile , 0 , SEEK_END);
          lSize = ftell (pFile); printf(" The file size is = %ld\n",lSize);
          rewind (pFile);
        
          buffer = (char*) malloc (sizeof(char)*lSize);
          if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
        
          result = fread (buffer,1,lSize,pFile);
          
          puts(buffer);
          if (result != lSize) {fputs ("Reading error",stderr); exit (3);}
          fclose (pFile);
          free (buffer);
          return 0;
        }

        Comment

        • agsrinivasan
          New Member
          • Feb 2007
          • 15

          #5
          yeah,
          i know that ,but,this is not my question...i have to search one word from this text file..


          Thanking you,

          srinivas

          Comment

          • kvbreddy
            New Member
            • Feb 2007
            • 23

            #6
            Hi Srinivasan,
            What ever the code u have written that works fine for the small input files. Getting entire file content into a char buffer is not good for larger files.
            So, better read word by word and search it.

            1) Open file.
            2) loop until EOF
            Read word
            If the word is matched
            break
            loop end

            Comment

            • agsrinivasan
              New Member
              • Feb 2007
              • 15

              #7
              hi...

              i had coded like below....

              Code:
              #include <stdlib.h>
              #include<string.h>
              
              int main (void) {
                
              	FILE *Input;
              	
              	long lSize;
              
                      Input = fopen("/home/srinivas/Desktop/cl.txt","r+");
              
              	if (Input ==NULL) {fputs ("File error",stderr); exit (1);}
              
              	fseek (Input ,0 , SEEK_END);
               		
              	lSize = ftell (Input); printf(" The file size is = %ld",lSize);
              
                      char string1[24];
                      
                       
                      printf("\n Enter the string you want to search \n");
              
              	gets(string1);
              
                      printf("\n The read string is =%s ",string1 ); 
              
                     //do{
                     
                      int i=0;
              	char string2[24];
              
              	
              
               /* Read one word for the text file */
              
              	do{
                           while( fgets(string2,20,Input) != '\0')
                            {
              		//string2[i] = fgetc(Input);
                              //printf("%c",string2);
              		//i++;
              	      }
                           
              	printf("the string2 is %s =",string2);
              	printf(" In do loop"); 
                          
              
                      if( strcmp(string1,string2) == 0)
                       {
              		printf(" string successfully searched : string2 = %s",string1);
                               break;
              		}
              
              	else
              	    {	printf(" string Not found");
              		}
                       }while(!feof(Input));
              
              
                          }
              I got output Like below....


              The file size is = 647579
              Enter the string you want to search
              SELVA

              The read string is =SELVA the string2 is \uffff\u04bf\uf fff\uffff\uffff \uffff,\uffff\u ffff\uffff\u04b f\uffff\uffffSE LVA = In do loop string Not foundsuse:


              wheather my code is correct???

              for searching a word in a file....

              Comment

              • kvbreddy
                New Member
                • Feb 2007
                • 23

                #8
                This is ur code partly modified....

                Code:
                        rewind(Input);
                       /* Read one word for the text file */
                
                         while(!feof(Input))
                         {
                            fscanf(Input, "%s", string2);
                
                            printf("The string2 is: %s\n",string2);
                            
                            if ( strcmp(string1,string2) == 0)
                            {
                                printf("String successfully searched\n");
                                break;
                            }
                        }
                        if (feof(Input))
                        {
                            printf("string search failed\n");
                        }
                finally close the file.


                vijay
                Last edited by kvbreddy; Feb 13 '07, 03:55 PM. Reason: changes

                Comment

                • agsrinivasan
                  New Member
                  • Feb 2007
                  • 15

                  #9
                  Originally posted by kvbreddy
                  This is ur code partly modified....

                  rewind(Input);
                  /* Read one word for the text file */

                  while(!feof(Inp ut))
                  {
                  fscanf(Input, "%s", string2);

                  printf("The string2 is: %s\n",string2);

                  if ( strcmp(string1, string2) == 0)
                  {
                  printf("String successfully searched\n");
                  break;
                  }
                  }
                  if (feof(Input))
                  {
                  printf("string search failed\n");
                  }

                  finally close the file.


                  vijay

                  sorry vijay,
                  This file not working ,it was printing all names in the file...

                  i want to search One seperate word like "ABC" in text file...



                  Thanks,

                  srini...
                  Last edited by agsrinivasan; Feb 13 '07, 05:21 PM. Reason: change a file..

                  Comment

                  • kvbreddy
                    New Member
                    • Feb 2007
                    • 23

                    #10
                    no..no.. it's working. I have tested this.
                    can u post ur code again... i will see...

                    Originally posted by agsrinivasan
                    sorry vijay,
                    This file not working ,it was printing all names in the file...

                    i want to search One seperate word like "ABC" in text file...



                    Thanks,

                    srini...

                    Comment

                    • agsrinivasan
                      New Member
                      • Feb 2007
                      • 15

                      #11
                      Originally posted by kvbreddy
                      no..no.. it's working. I have tested this.
                      can u post ur code again... i will see...

                      I had tried one more method ...it is working successfully...


                      see the code....


                      Code:
                      #include <stdio.h>
                      #include <stdlib.h>
                      #include<string.h>
                      
                      int main (void) {
                        
                      	FILE *Input;
                      	
                      	long lSize;
                      
                               size_t result;
                      
                              char *buffer;
                      
                              Input = fopen("/home/srinivas/Desktop/cl.txt","r+");
                      	printf("Input value: %d\n",Input);
                      
                      	if (Input ==NULL) {fputs ("File error",stderr); exit (1);}
                      
                      	fseek (Input ,0 , SEEK_END);
                       		
                      	lSize = ftell (Input); printf(" The file size is = %ld\n",lSize);
                              
                              rewind (Input);
                      
                      	  // allocate memory to contain the whole file:
                      	  buffer = (char*) malloc (sizeof(char)*lSize);
                      	  if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
                      
                      	  // copy the file into the buffer:
                      	  result = fread (buffer,1,lSize,Input);
                      
                      	   long i,j,len,z;
                      
                                char string1[20];
                       
                                printf(" Enter the Name you want to search \n");
                      
                                 gets(string1);
                      
                                len = strlen(string1);
                      
                                //printf("The length of the string = %d ",len);
                      
                                 char string2[20];
                      
                                // char *compare;
                               
                      	fseek (Input ,0 , SEEK_SET);
                             
                      
                      	for(i=0;i <lSize ; i++)
                      	{
                      	  	//printf("%c ,%c \n ",string1[0],buffer[i]);
                      		if(string1[0] == buffer[i]){
                                     // printf("Inside if Loop\n");
                      	         for(z=0, j=i ;j < i+len  ;j++)
                      		{
                                            
                                         // printf("Inside for Loop\n");
                      	            string2[z] = buffer[j];
                                          z++;
                                        }
                             			
                               //  printf("The length of the string2= %d,%s ",strlen(string2),string2);
                      
                                    if(strcmp(string1,string2) == 0)
                          				{
                              				printf("string successfully searched\n ");
                           				}      
                                         
                                     			//else
                                                        //  printf("string Not found\n");
                      		}
                       }
                        
                         
                      
                      }

                      Comment

                      • agsrinivasan
                        New Member
                        • Feb 2007
                        • 15

                        #12
                        hi...
                        I have text file.one part of a file ..i given below..

                        7. LPA.SR 36917/2006 M/S.V.SELVARAJ
                        D. JAYASINGH
                        V.S.MANIMEKALAI
                        and
                        MP.SR 67318/2006
                        FOR EXTENSION OF TIME
                        ~~~~~~~~~~~~~~~ ~~~~~~

                        8. OSA.323/2006 M/S.AIYAR AND DOLIA M/S.RAM AND RAJAN &amp; ASSOCTS.
                        V. KALYANARAMAN FOR R1
                        R2 OFFICIAL LIQUIDTOR
                        R3 TIMES GURANTEE LTD MUMBAI - 1
                        and
                        OSA.324/2006
                        MP.1/2006
                        MP.2/2006
                        FOR DIRECTION
                        ~~~~~~~~~~~~~

                        9. (NOT READY IN NOTICE)
                        WA.1246/1998 M/S K.BALASUBRAMANI AN MR.M.V.VENKATAS ESHAN FOR R1
                        and
                        CMP.13730/1998
                        WA.1247/1998 MR.A.FATHIMANAT HAN MR.M.V.VENKATAS ESHAN FOR R3
                        and
                        CMP.13731/1998
                        FOR JUDGMENT
                        ~~~~~~~~~~~~


                        Now what my next plan is ...I have to search one string..that was done already...

                        I have to put tags for eg..$$ into before starting of serial No 7..and also put tag into befor serial no 8...

                        ------------------------------------------------------------------------------------------------------------
                        for eg....
                        $$ 7. LPA.SR 36917/2006 M/S.V.SELVARAJ
                        D. JAYASINGH
                        V.S.MANIMEKALAI
                        and
                        MP.SR 67318/2006
                        FOR EXTENSION OF TIME
                        ~~~~~~~~~~~~~~~ ~~~~~~ $$

                        8. OSA.323/2006 M/S.AIYAR AND DOLIA M/S.RAM


                        -------------------------------------------------------------------------------------------------------------
                        This is my requirement...


                        give me suggestions

                        Comment

                        • friendjin
                          New Member
                          • Feb 2007
                          • 19

                          #13
                          try: strstr

                          Code:
                          while(!file.eof())
                          {
                          setline(file,&line);
                          strstr(line, "ABC")
                          }
                          look up strstr command

                          Comment

                          • friendjin
                            New Member
                            • Feb 2007
                            • 19

                            #14
                            otherwise you can do a simple way but not good. but i am sure it is working.

                            Code:
                            char SearchName[4]= "ABV";
                            int time;
                            for (time=0, time< 1000, time++)  // time value depends the size of the file
                            {
                            scanf ("%c", &buffer[time]);
                            while(SearchName[0]==buffer[time])
                            						
                            {   
                            							time++;
                            							while(SearchName[1]==buffer[time])
                            							
                            {
                            								time++;
                            								while(SearchName[2]==buffer[time])
                            								{
                            															//search successful.		
                            								}
                            
                            }
                            
                            }
                            }

                            Comment

                            Working...