You are here:

C/Replacing a word

Advertisement


Question
Sir,
I want to find the occurence of a word in a text file and replace it with another word.How can I do this?Please help.Thank you.
-Varshini.

Answer
Are you trying to write C code for this?
Here is how you can do that:
1. Read the complete contents into a buffer.
2. Search for the word in the buffer.
3. Now find the difference in sizes between the word and the replacement word.
4. If the new word is bigger (by say 3 characters), then push all the characters from the end of the word by that many characters and make space for the new word.
5. Goto 9
6. If the new word is smaller (by say 2 characters), then copy the new word in place of original word.
7. Squeeze the buffer by that many characters that was the difference.
8. Goto 10.
9. Copy the new word in place of the old one.
10. Write the buffer back to the file and close the file.
11. End

Hope this helps....

-ssnkumar

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Narendra

Expertise

I can answer questions in C related to programming, data structures, pointers and file manipulation. I use Solaris for doing C code and if you have questions related to C programming on Solaris, I will be able to help better.

Experience

6.5

Organizations belong to
Sun Microsystems

Awards and Honors
Brain Bench Certified Expert C programmer.
Advanced System Software Certified

©2012 About.com, a part of The New York Times Company. All rights reserved.