search and replace 
Author Message
 search and replace

I need to open a text file, do a search and replace and save the results in
a new file.

Example.
String from source text file.
G00 200.000

Desired string in new target file
MOVEABS 200.00

I'm new to C, and would appreciate some guidence.



Wed, 18 Dec 2002 03:00:00 GMT  
 search and replace


Quote:
> I need to open a text file, do a search and replace and save the
results in
> a new file.

> Example.
> String from source text file.
> G00 200.000

> Desired string in new target file
> MOVEABS 200.00

> I'm new to C, and would appreciate some guidence.

Study functions fopen, fgets, fprintf, fputc, remove, rename, and
strstr.

If you are aware of the length of the largest line in the file, you
can simply use function fgets to read the file. Read each line into a
chararacter array. Use function strstr to determine if the search
string is in that array. Then copy the line, possible modified with
the replacement string. to a temp file. Once reading the source file
is completed, delete it and rename the temp file.

nclude <stdio.h>
#include <string.h>

#define MAX_FILE_LEN 156

int fsearch_replace(const char *fname, const char *f, const char *r) {
   char *s, *s1 ,buf[MAX_FILE_LEN];
   int result = 0;
   FILE *fpi, *fpo;

   if((fpi = fopen(fname,"r")) == NULL) return -1;
   if((fpo = fopen("temp.txt", "w")) == NULL) {
      fclose(fpi);
      return -1;
      }
   while(1) {
      if(NULL == fgets(buf, sizeof buf, fpi)) break;
      if((s = strstr(buf,f)) == NULL) {
         fprintf(fpo,"%s",buf);
         fflush(fpo);
         }
      else {
         result++;
         for(s1 = buf; s1 != s; s1++) fputc(*s1,fpo);
         fprintf(fpo,"%s",r);
         s += strlen(f);
         fprintf(fpo,"%s",s);
         }
      }
   remove(fname);
   rename("temp.txt",fname);
   return result;
   }

int main(void) {
   int found;

   if((found = fsearch_replace("test.txt", "G00", "CRONTAB")) > -1)
      printf("Found and replaced %d occurances of %s\n",found,"G00");
   else puts("Unable to search file");
   return 0;
   }

--
Al Bowers
http://www.geocities.com/abowers822

C-faq: http://www.eskimo.com/~scs/C-faq/top.html
GIBCO Labs.
Tampa FL. USA.

Sent via Deja.com http://www.deja.com/
Before you buy.



Wed, 18 Dec 2002 03:00:00 GMT  
 
 [ 2 post ] 

 Relevant Pages 

1. Search and Replace facility

2. Newbie: Sub-String search and replace routine

3. Newbie: Sub-String search and replace routine

4. Optimization problem search and replace

5. String - search and replace

6. search and replace strings with lists

7. how to do search and replace?

8. search and replace

9. regex search and replace

10. How to Search&Replace C Data Types ?

11. Binary file Search and Replace

12. search and replace in a string

 

 
Powered by phpBB® Forum Software