使用C文件中的字符串替换 [英] string replace in file using C

查看:169
本文介绍了使用C文件中的字符串替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还没有在思考阶段实现这一点,我还在,但我必须要经过一个文件,并替换某些字符串用另一个字符串。例如,

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" ...

应成为

<img src="/proxy/www.example.com/images/logo.gif" ...

我如何能处理这有什么建议?或许存在一些字符串替换C函数,会为我做到这一点,我不知道......?

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

推荐答案

没有,但在C中没有函数,整个文件替换字符串。你必须自己实现它。

No, there is no function in C that replaces a string throughout a file. You must implement it yourself.

这是说,什么你展示我们的是HTML和HTML是棘手的,因为它是分层的。你需要正确地分析它?因为如果是,任务困难得多。鉴于它的功课,我对此表示怀疑,所以你可能会被做足够的:

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:


  1. 打开文件,并将其加载到内存中(假设它是不是太大 - 如果是这样,你可以写到一个临时文件,并将其移动到原来选好​​后)

  2. 连续使用的strstr 找到你需要开始更换锚字符串

  3. 替换

  4. 重复2和3,直到完成了文件

  5. 写文件回

  1. open the file and load it to memory (assuming it isn't too large - if it is, you can write into a temporary file and move it onto the original one after you've finished)
  2. continuously use strstr to find the anchor string you need to start replacing
  3. replace
  4. repeat 2 and 3 until finished with file
  5. write file back

这篇关于使用C文件中的字符串替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆