在一个文件中替换的单词,用C [英] Replacing a word in a file, using C

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

问题描述

我如何在一个文件中使用 C 另一个词替换词吗?

How do I replace a word in a file with another word using C?

例如,我有一个包含一个文件:

For example, I have a file which contains:

my friend name is sajid

我要替换的单词的朋友的用的爷爷的,使得文件更改为:

I want to replace the word friend with grandfather, such that the file is changed to:

my grandfather name is sajid 

(我开发的Ubuntu Linux操作系统。)

(I am developing on Ubuntu Linux.)

我在做C.申请我创建了一个.txt文件和一些数据写入到它,但我的计划的进展我要搜索一些文字,并与其他词代替它。我现在面临的问题是,假设在我的文件,我写

I am doing filing in C. I have created a .txt file and write some data into it, but as my program progresses I have to search some text and replace it with the other words. The problem I am facing is that suppose in my file I wrote

"I bought apple from the market"

如果我取代苹果,菠萝苹果有5个char和菠萝有9烧焦就会把它写成

If i replace apple with pineapples as apple has 5 char and pineapple has 9 char it will write it as

"I bought pineapple m the market"

这也影响了苹果后写的话。

It also has affected the words written after apple.

我用C做,不是一个命令行脚本。

I have to do it using C, not a command line script.

推荐答案

当你已经意识到,你将不能够使地方在改变原始文件。

As you've realized, you won't be able to make the change in place in the original file.

简单的解决方法是阅读从原来的文件中的每个字符串,并将其写入标准输出,使得更换是必要的。在伪code:

The easy solution is to read each string from the original file and write it to standard output, making the replacement as necessary. In pseudocode:

open original file
while not at end of original file
  get next string from original file
  if string == "friend"
    write "grandfather" to standard output
  else
    write string to standard output
end while

您可以然后将输出重定向到另一个文件,当你执行它,类似于如何 SED AWK 工作。

You can then redirect the output to another file when you execute it, similar to how sed and awk work.

另外,您可以创建在code目标文件,并直接写入。如果你需要用新的文件来替换原文件,你可以使用删除()重命名() STDIO 的库函数。

Alternately, you can create a destination file in the code and write to it directly. If you need to replace the original file with the new file, you can use the remove() and rename() library functions in stdio.

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

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