473,383 Members | 1,952 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

search a string in text file in C

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
Feb 12 '07 #1
13 16102
r035198x
13,262 8TB
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.
Feb 12 '07 #2
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....

Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include<string.h>
  4.  
  5. int main () {
  6.   FILE * pFile;
  7.   long lSize;
  8.   char * buffer;
  9.   size_t result;
  10.  
  11.   pFile = fopen ( "/home/srinivas/Desktop/cl.txt" , "r+" );
  12.   if (pFile==NULL) {fputs ("File error",stderr); exit (1);}
  13.  
  14.   // obtain file size:
  15.   fseek (pFile , 0 , SEEK_SET);
  16.   lSize = ftell (pFile); printf(" The file size is = %ld",lSize);
  17.   rewind (pFile);
  18.  
  19.   // allocate memory to contain the whole file:
  20.   buffer = (char*) malloc (sizeof(char)*lSize);
  21.   if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
  22.  
  23.   // copy the file into the buffer:
  24.   result = fread (buffer,1,lSize,pFile);
  25.  
  26.   puts(buffer);
  27.   if (result != lSize) {fputs ("Reading error",stderr); exit (3);}
  28.  
  29. fclose (pFile);
  30.   free (buffer);
  31.   return 0;
  32. }
Feb 12 '07 #3
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.

Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include<string.h>
  4.  
  5. int main () {
  6.   FILE * pFile;
  7.   long lSize;
  8.   char * buffer;
  9.   size_t result;
  10.  
  11.   pFile = fopen ( "/mydir2/narasip/zippy.c" , "r+" );
  12.   if (pFile==NULL) {fputs ("File error",stderr); exit (1);}
  13.  
  14.   fseek (pFile , 0 , SEEK_END);
  15.   lSize = ftell (pFile); printf(" The file size is = %ld\n",lSize);
  16.   rewind (pFile);
  17.  
  18.   buffer = (char*) malloc (sizeof(char)*lSize);
  19.   if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
  20.  
  21.   result = fread (buffer,1,lSize,pFile);
  22.  
  23.   puts(buffer);
  24.   if (result != lSize) {fputs ("Reading error",stderr); exit (3);}
  25.   fclose (pFile);
  26.   free (buffer);
  27.   return 0;
  28. }
Feb 13 '07 #4
yeah,
i know that ,but,this is not my question...i have to search one word from this text file..


Thanking you,

srinivas
Feb 13 '07 #5
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
Feb 13 '07 #6
hi...

i had coded like below....

Expand|Select|Wrap|Line Numbers
  1. #include <stdlib.h>
  2. #include<string.h>
  3.  
  4. int main (void) {
  5.  
  6.     FILE *Input;
  7.  
  8.     long lSize;
  9.  
  10.         Input = fopen("/home/srinivas/Desktop/cl.txt","r+");
  11.  
  12.     if (Input ==NULL) {fputs ("File error",stderr); exit (1);}
  13.  
  14.     fseek (Input ,0 , SEEK_END);
  15.  
  16.     lSize = ftell (Input); printf(" The file size is = %ld",lSize);
  17.  
  18.         char string1[24];
  19.  
  20.  
  21.         printf("\n Enter the string you want to search \n");
  22.  
  23.     gets(string1);
  24.  
  25.         printf("\n The read string is =%s ",string1 ); 
  26.  
  27.        //do{
  28.  
  29.         int i=0;
  30.     char string2[24];
  31.  
  32.  
  33.  
  34.  /* Read one word for the text file */
  35.  
  36.     do{
  37.              while( fgets(string2,20,Input) != '\0')
  38.               {
  39.         //string2[i] = fgetc(Input);
  40.                 //printf("%c",string2);
  41.         //i++;
  42.           }
  43.  
  44.     printf("the string2 is %s =",string2);
  45.     printf(" In do loop"); 
  46.  
  47.  
  48.         if( strcmp(string1,string2) == 0)
  49.          {
  50.         printf(" string successfully searched : string2 = %s",string1);
  51.                  break;
  52.         }
  53.  
  54.     else
  55.         {    printf(" string Not found");
  56.         }
  57.          }while(!feof(Input));
  58.  
  59.  
  60.             }
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\uffff\uffff\uffff\uffff,\uffff\uffff\ uffff\u04bf\uffff\uffffSELVA = In do loop string Not foundsuse:


wheather my code is correct???

for searching a word in a file....
Feb 13 '07 #7
This is ur code partly modified....

Expand|Select|Wrap|Line Numbers
  1.         rewind(Input);
  2.        /* Read one word for the text file */
  3.  
  4.          while(!feof(Input))
  5.          {
  6.             fscanf(Input, "%s", string2);
  7.  
  8.             printf("The string2 is: %s\n",string2);
  9.  
  10.             if ( strcmp(string1,string2) == 0)
  11.             {
  12.                 printf("String successfully searched\n");
  13.                 break;
  14.             }
  15.         }
  16.         if (feof(Input))
  17.         {
  18.             printf("string search failed\n");
  19.         }
finally close the file.


vijay
Feb 13 '07 #8
This is ur code partly modified....

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

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...
Feb 13 '07 #9
no..no.. it's working. I have tested this.
can u post ur code again... i will see...

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...
Feb 14 '07 #10
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....


Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include<string.h>
  4.  
  5. int main (void) {
  6.  
  7.     FILE *Input;
  8.  
  9.     long lSize;
  10.  
  11.          size_t result;
  12.  
  13.         char *buffer;
  14.  
  15.         Input = fopen("/home/srinivas/Desktop/cl.txt","r+");
  16.     printf("Input value: %d\n",Input);
  17.  
  18.     if (Input ==NULL) {fputs ("File error",stderr); exit (1);}
  19.  
  20.     fseek (Input ,0 , SEEK_END);
  21.  
  22.     lSize = ftell (Input); printf(" The file size is = %ld\n",lSize);
  23.  
  24.         rewind (Input);
  25.  
  26.       // allocate memory to contain the whole file:
  27.       buffer = (char*) malloc (sizeof(char)*lSize);
  28.       if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
  29.  
  30.       // copy the file into the buffer:
  31.       result = fread (buffer,1,lSize,Input);
  32.  
  33.        long i,j,len,z;
  34.  
  35.           char string1[20];
  36.  
  37.           printf(" Enter the Name you want to search \n");
  38.  
  39.            gets(string1);
  40.  
  41.           len = strlen(string1);
  42.  
  43.           //printf("The length of the string = %d ",len);
  44.  
  45.            char string2[20];
  46.  
  47.           // char *compare;
  48.  
  49.     fseek (Input ,0 , SEEK_SET);
  50.  
  51.  
  52.     for(i=0;i <lSize ; i++)
  53.     {
  54.           //printf("%c ,%c \n ",string1[0],buffer[i]);
  55.         if(string1[0] == buffer[i]){
  56.                // printf("Inside if Loop\n");
  57.              for(z=0, j=i ;j < i+len  ;j++)
  58.         {
  59.  
  60.                    // printf("Inside for Loop\n");
  61.                 string2[z] = buffer[j];
  62.                     z++;
  63.                   }
  64.  
  65.          //  printf("The length of the string2= %d,%s ",strlen(string2),string2);
  66.  
  67.               if(strcmp(string1,string2) == 0)
  68.                     {
  69.                         printf("string successfully searched\n ");
  70.                      }      
  71.  
  72.                            //else
  73.                                   //  printf("string Not found\n");
  74.         }
  75.  }
  76.  
  77.  
  78.  
  79. }
Feb 15 '07 #11
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.BALASUBRAMANIAN MR.M.V.VENKATASESHAN FOR R1
and
CMP.13730/1998
WA.1247/1998 MR.A.FATHIMANATHAN MR.M.V.VENKATASESHAN 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
Feb 15 '07 #12
try: strstr

Expand|Select|Wrap|Line Numbers
  1. while(!file.eof())
  2. {
  3. setline(file,&line);
  4. strstr(line, "ABC")
  5. }
look up strstr command
Feb 15 '07 #13
otherwise you can do a simple way but not good. but i am sure it is working.

Expand|Select|Wrap|Line Numbers
  1. char SearchName[4]= "ABV";
  2. int time;
  3. for (time=0, time< 1000, time++)  // time value depends the size of the file
  4. {
  5. scanf ("%c", &buffer[time]);
  6. while(SearchName[0]==buffer[time])
  7.  
  8. {   
  9.                             time++;
  10.                             while(SearchName[1]==buffer[time])
  11.  
  12. {
  13.                                 time++;
  14.                                 while(SearchName[2]==buffer[time])
  15.                                 {
  16.                                                             //search successful.        
  17.                                 }
  18.  
  19. }
  20.  
  21. }
  22. }
Feb 15 '07 #14

Sign in to post your reply or Sign up for a free account.

Similar topics

60
by: Julie | last post by:
What is the *fastest* way in .NET to search large on-disk text files (100+ MB) for a given string. The files are unindexed and unsorted, and for the purposes of my immediate requirements, can't...
32
by: tshad | last post by:
Can you do a search for more that one string in another string? Something like: someString.IndexOf("something1","something2","something3",0) or would you have to do something like: if...
1
by: Eric | last post by:
Hi: I have two files. I search pattern ":" from emails text file and save email contents into a database. Another search pattern " field is blank. Please try again.", vbExclamation + vbOKOnly...
4
by: Dameon | last post by:
Hi All, I have a process where I'd like to search the contents of a file(in a dir) for all occurences (or the count of) of a given string. My goal is to focus more on performance, as some of the...
1
by: nganglove | last post by:
C++ string search -------------------------------------------------------------------------------- Hello, please can any one help me? I am given an assigment in C++ to read a text file and...
2
by: princymg | last post by:
I want to search a file from server and want to copy it to the local disk. how it is done? This is working if the file is in my hard disk itself.But not when it comes to server. If i map the server...
3
by: =?Utf-8?B?UGVycmlud29sZg==?= | last post by:
Not sure where to post this... Found some interesting behavior in Windows Search (Start =Search =All files and folders =search for "A word or phrase in the file:"). This applies to XP and maybe...
2
by: slizorn | last post by:
hi guys, i need to make a tree traversal algorithm that would help me search the tree.. creating a method to search a tree to find the position of node and to return its pointer value basically i...
0
by: JamesOo | last post by:
I have the code below, but I need to make it searchable in query table, below code only allowed seach the table which in show mdb only. (i.e. have 3 table, but only can search either one only,...
0
Debadatta Mishra
by: Debadatta Mishra | last post by:
Introduction In this article I will provide you an approach to manipulate an image file. This article gives you an insight into some tricks in java so that you can conceal sensitive information...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.