search a string in a file

This is a discussion on search a string in a file within the C Programming forums, part of the General Programming Boards category; Hi, This is an existing code from this site which is supposed to find a desired string in the file ...

  1. #1
    hjr
    hjr is offline
    Registered User
    Join Date
    Oct 2009
    Posts
    6

    search a string in a file

    Hi,
    This is an existing code from this site which is supposed to find a desired string in the file and replaces it on its occurance.
    I tried compiling this code n it doesn't seem to append the string Replacetext(Help) in the FILE fp. But however it does write into the FILE fout on the occurance of String SearchText(Hello). I tried adding fflush(fp) into the code . but it doesn't seem to help. can somebody figure out whats happening. I did a single step trace on the code n it does replace it. after complete execution when i open the file fp(log.txt) replaced string does not exist. i have pasted the entire piece of code. really appreciate ur help.
    Code:
    #include<stdio.h>
    #include<string.h>
    #include<conio.h>
    #include<stdlib.h>
    
    void main()
    {
    FILE *fp,*fout;
    int i=0,len_string;
    char SearchText[]="Hello"; /* You can replace this text */
    char ReplaceText[]="Help"; /*You can also replace this text. */
    char temp[30];
    fp=fopen("log.txt","a+");
    fout=fopen("temp.txt","a+");
    rewind(fp); /* for going to start of file. */
    if(fp==NULL || fout==NULL)
    {
    printf("File couldn't be opened ");
    exit(0);
    }
    len_string=strlen(SearchText);
    while(!feof(fp))
    {
    for(i=0;i<len_string;i++) temp[i]=fgetc(fp);
    temp[i]='\0';
    if(stricmp(SearchText,temp)==0) /* the stricmp() is used for comparing both string. */
    {
    	
    fprintf(fp,"%s ",ReplaceText);
    fprintf(fout,"%s",ReplaceText);
    fflush(fp);
    fclose(fp);
    fclose(fout);
    exit(1);
    }
    fseek(fp,-(len_string-1),1);
    }
    fclose(fp);
    fclose(fout);
    }

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Append is not the same as replace. Which is it that you want to do?

    Appending is simple, just open the file in append mode, and add on the desired text.

    Replacing is more work, and there are two ways to do that:

    1) If the file is in a "record" for fixed field type of format with the data, then you just need to set your text into the same sized field, and the file can be over-written, directly.

    Note that this won't work if the text is 40 bytes, and the field is 20 bytes long, of course.

    This would use binary file mode, usually.

    2) If the file is not in the above mentioned format, (most files would certainly not be), then you need to:

    a) check the size in bytes of the text you want to add, and compare it with the text you want to replace. If they are the same, you can replace it directly, by over-writing.

    b) if the sizes don't match (and can't be made to match), then you need to read in the file, (writing out the contents to a temporary file as you go), until you get to the string you want to replace. Then write out the string you want to add, instead of the string you want to replace, into the temporary file.

    c) now delete the old file and re-name the temporary file, with the old file name.

    Indenting your code, would help you find your bugs, much easier. Us too.

  3. #3
    hjr
    hjr is offline
    Registered User
    Join Date
    Oct 2009
    Posts
    6
    "append is not same as replace". i agree on that. I haven't yet attempted on the replace part as yet. but i did get an idea from u said.. i definitely try that

    first since I want to append let me attempt on the appending part of the program

    let me give u an example
    Let this be the contents of log.txt.
    Searchtext[]="love" and Replace text[]="like";

    "Welcome to C. I love C programming."
    This should be the end result

    Result -- "Welcome to C. I lovelike ogramming".

    _base of fp has this when I trace(single step) this file. Now when i close this file and open what should I find in log.txt.
    Shouldn't the file contents be "Welcome to C. I lovelike ogramming"????
    I want this to Happen. BTW my apologies for the indentation part. Sorry abt that.

  4. #4
    hjr
    hjr is offline
    Registered User
    Join Date
    Oct 2009
    Posts
    6
    one more thing, it is a text file. Actually I have tried appending both in text and binary.

  5. #5
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    I don't think you understand what the word 'append' means. Let's take your example:

    Welcome to C. I like...

    There, you've just found the word like. Now you need to back up strlen( "like" ) spaces, so that you can overwrite it. You don't appear to be doing that. Then you write over top of it. Now, this only works because the words are the exact same length. Then you continue on. Anyway, appending is just adding to the end of the file. So that's not what you want (as you've been told already).

    But the problem you're facing now, is that you're finding 'like' but in doing so, you're past the word. You need to back up and overwrite it. Again, this only works because the replacement word is the exact same length as the word you're replacing. So it's not the ideal solution.


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

  6. #6
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by hjr View Post

    first since I want to append let me attempt on the appending part of the program

    let me give u an example
    Let this be the contents of log.txt.
    Searchtext[]="love" and Replace text[]="like";

    "Welcome to C. I love C programming."
    This should be the end result

    Result -- "Welcome to C. I lovelike ogramming".

    _base of fp has this when I trace(single step) this file. Now when i close this file and open what should I find in log.txt.

    Shouldn't the file contents be "Welcome to C. I lovelike ogramming"????
    I want this to Happen. BTW my apologies for the indentation part. Sorry abt that.
    Your result shows neither an append of the word "like", nor a replacement:

    Code:
    Original: 
    "Welcome to C. I love programming."
    
     "Welcome to C. I lovelike ogramming."
    
    An append would be:
    "Welcome to C. I love programming.like"
    
    A replacement would be:
    "Welcome to C. I like programming."

    A normal append might involve removing the period at the end of the last sentence, and adding a space as well, before appending the last word or phrase.

    I love programming like, however, makes no sense, in English grammar. In your example, only a replacement of the word "love" with the word "like", makes a good English sentence.

    I can show you how to do this, but you need to be *really* specific about what you want. As Quzah has mentioned above, the program changes the moment you want to replace a word of one length, with a different sized word.

    I'd recommend making the changes in a large buffer in an array of type char, rather than trying to make the changes directly on the file itself.
    Last edited by Adak; 10-11-2009 at 11:41 AM.

  7. #7
    Dr Dipshi++ mike_g's Avatar
    Join Date
    Oct 2006
    Location
    On me hyperplane
    Posts
    1,218
    Any reason why you need C for this?

    In python you could just do:
    Code:
    file = open("myfile.txt", "r+")
    data = file.read().replace("texttoreplace", "newtext")
    file.seek(0)
    file.write(data)
    file.close()

  8. #8
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by mike_g View Post
    Any reason why you need C for this?
    a) He's on the C board.
    b) He's in school taking a C course.
    c) Both of the above.


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

  9. #9
    Dr Dipshi++ mike_g's Avatar
    Join Date
    Oct 2006
    Location
    On me hyperplane
    Posts
    1,218
    He's in school taking a C course.
    Who said that? If its educational then its fine. If its just a matter of getting a task done then it make sense to do it the easy way.

  10. #10
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Maybe it's not for school. Maybe it's just to learn (which looks to be the case). Anyway, upon reviewing the first post, he's going through some code he found on the site--which indicates that he wants to learn how to do it in C. Suggesting he use another programming language is like suggesting I just open the file in notepad and do a search-and-replace.


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

  11. #11
    hjr
    hjr is offline
    Registered User
    Join Date
    Oct 2009
    Posts
    6
    I want this particular thing to happen with the piece of code I have pasted.
    "Welcome to C. I love programming.like"

    That is not happening. I want to figure out why that is not happening. There is defninitely a small flaw in the code why it is not appending.

    I am a student and Coding can be done in 100 different ways.
    if u could make the below sentence to work with the same code that i pasted

    "Welcome to C. I love programming.like" this is fine with me...
    damn nothing is being written into log.txt not in the middle not at the end

  12. #12
    hjr
    hjr is offline
    Registered User
    Join Date
    Oct 2009
    Posts
    6
    mike_g thanks for all the help..but had i known python why will I be posting a help in the C forum. for me to proceed with my assignment nothing is being changed in the file after appending...had something been written i could proceed with so many other functions fgetpos fsetpos some how gone ahead....nothing is being changed after closing the file...something that i am not aware(which of course i want to learn) of is happening in the code

  13. #13
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    I'm looking at your program, right now.

    Well, this has been fun!

    I'm not that well versed with string handling functions that are in the standard headers, so
    I'm learning a lot here.

    I thought this was interesting, and I'd say use this string function, instead of your current one. I couldn't get
    your function to find the target string.

    I'm re-arranging your program quite a bit, but it should give you some idea's. I'll post it when it's ok.

    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main(void)
    {
       char *str1 = "Hello World", *str2 = "or", *ptr;
    
       ptr = strstr(str1, str2);
       printf("The substring is: %d\n", ptr-str1);
       return 0;
    }
    If ptr is NULL, then the target string wasn't found.

    Edit:

    This is my take on doing a search for a target string, through a file, and appending a string to the file, if the target string was found.

    I haven't tried it yet on any file longer than BUFSIZ, however.

    Code:
    //searches a file for a target string. If it's found, it appends a string, onto the file.
    
    #include<stdio.h>
    #include<string.h>
    
    int main() {
      FILE *fp;
      int gotit;
      char *ptr;
      char buff[BUFSIZ];
      char target[]= "love"; 
      char append[]="like"; 
      
      fp=fopen("log.txt","at+");
    
      if(fp==NULL)  {          
        printf("File couldn't be opened ");
        return 1;
      }
      gotit = 0;
      while(fgets(buff, BUFSIZ, fp)) {
        ptr = strstr(buff, target); 
        if(ptr) {
          printf("\n The substring starts at the %d char", ptr-buff);
          printf("\n Target string was found, appending replacement text");
          rewind(fp);
          fprintf(fp, "%s", append);
          gotit = 1;
          break;
        }
      }
      fflush(fp);
      fclose(fp);
    
      if(!gotit) 
        printf("\n The target string was not found");
    
      printf("\n\n\t\t\t     press enter when ready");
      gotit = getchar(); 
      return 0;
    }
    Last edited by Adak; 10-11-2009 at 03:29 PM.

  14. #14
    Banned
    Join Date
    May 2007
    Location
    Berkeley, CA
    Posts
    329
    This is some really bad C code. Here are some of the really gross errors that I can see...

    Quote Originally Posted by hjr View Post
    Hi,
    This is an existing code from this site which is supposed to find a desired string in the file and replaces it on its occurance.
    I tried compiling this code n it doesn't seem to append the string Replacetext(Help) in the FILE fp. But however it does write into the FILE fout on the occurance of String SearchText(Hello). I tried adding fflush(fp) into the code . but it doesn't seem to help. can somebody figure out whats happening. I did a single step trace on the code n it does replace it. after complete execution when i open the file fp(log.txt) replaced string does not exist. i have pasted the entire piece of code. really appreciate ur help.
    Code:
    #include<stdio.h>
    #include<string.h>
    #include<conio.h>
    conio.h isn't a standard header file. I have no idea what the header file does since it doesn't exist on my computer.

    Code:
    #include<stdlib.h>
    
    void main()
    void main() isn't recognized by the GNU C compiler on my Linux box.

    Code:
    {
    
    FILE *fp,*fout;
    int i=0,len_string;
    char SearchText[]="Hello"; /* You can replace this text */
    char ReplaceText[]="Help"; /*You can also replace this text. */
    char temp[30];
    30 is a what is known as a "magic number"

    Code:
    fp=fopen("log.txt","a+");
    fout=fopen("temp.txt","a+");
    rewind(fp); /* for going to start of file. */
    if(fp==NULL || fout==NULL)
    {
    printf("File couldn't be opened ");
    exit(0);
    }
    printf() isn't going to get flushed() on the next call.


    Code:
    len_string=strlen(SearchText);
    while(!feof(fp))
    You end up reading the string twice before you reach EOF.

    Code:
    {
    for(i=0;i<len_string;i++) temp[i]=fgetc(fp);
    temp[i]='\0';
    if(stricmp(SearchText,temp)==0) /* the stricmp() is used for comparing both string. */
    {
    	
    fprintf(fp,"%s ",ReplaceText);
    fprintf(fout,"%s",ReplaceText);
    fflush(fp);
    fclose(fp);
    fclose(fout);
    exit(1);
    }
    fseek(fp,-(len_string-1),1);
    }
    fclose(fp);
    fclose(fout);
    }
    Last edited by Overworked_PhD; 10-11-2009 at 06:23 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Newbie homework help
    By fossage in forum C Programming
    Replies: 3
    Last Post: 04-30-2009, 04:27 PM
  2. String issues
    By The_professor in forum C++ Programming
    Replies: 7
    Last Post: 06-12-2007, 09:11 AM
  3. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 09:33 PM
  4. Something is wrong with this menu...
    By DarkViper in forum Windows Programming
    Replies: 2
    Last Post: 12-14-2002, 10:06 PM

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21