I haven't yet implemented this, I'm still in the thinking stage, but I have to go through a file and replace a certain string with another string. For example,
<img src="/images/logo.gif" ...
should become
<img src="/proxy/www.example.com/images/logo.gif" ...
Any advice on how I can approach this? Perhaps there exist some "string replace" C functions that would do this for me that I don't know about...?
Right now, if I had to write this function myself, I would give it as parameters the file, string to replace, replacement string. Then I would manually go through the file and look for an occurrence of the string and recreate it. This, however, seems very inefficient. Are there better ways to do this?
Thanks, Hristo
First of all, C is an awesome language, but is one of the most painful languages to do this type of operation in. Just had to say it.
Can you safely assume that the contents of the entire file can fit in memory? If so:
Since it's homework I'm going with the assumption that the string can not span multiple lines. If this assumption is correct (and barring the complications with "replacing text in HTML") then:
1 Read the next line
2 Replace string and write line (to another file)
3 If not at end, goto #1
4 Win \o/
Or perhaps the teacher wants something else shrug
You should investigate the sed command. See what it does and do something similar.
It works as a filter, so when using it to replace something in a file what you often do is capture the output into a file and then replace the old file with the new file.
Are you try strcpy function for this,
Assign the url in one string and replace it by strcpy function.
No, there is no function in C that replaces a string throughout a file. You must implement it yourself.
That said, what you're showing us is HTML, and HTML is tricky, because it's hierarchical. Are you required to correctly parse it? Because if you are, the task is much more difficult. Seeing that it's homework, I doubt it, so you might do enough by:
strstr
to find the anchor string you need to start replacingYou can use following program to search & replace string in a file.