Replacing a word in a file, using C

后端 未结 2 1152
伪装坚强ぢ
伪装坚强ぢ 2021-01-29 02:33

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
相关标签:
2条回答
  • 2021-01-29 03:11

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

    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
    

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

    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.

    0 讨论(0)
  • 2021-01-29 03:18

    How about using the exiting Linux sed program?

    sed -i 's/friend/grandfather/' filename

    That will replace friend with grandfather in the existing file. Make a copy first if you want to keep the original!

    Edit:

    Alternatively, load the file into an STL string, replace 'friend' with 'grandfather' using a technique such as this, and save the new string into a file.

    0 讨论(0)
提交回复
热议问题