且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用C替换文本文件中的行

更新时间:2023-02-23 17:16:34

执行所需操作的***方法是使用sed之类的实用程序.它比您(或我)所写的任何东西都更快,并且使用的内存更少.

The best way of doing what you want is to use a utility like sed. It is faster and uses less memory than anything you (or I) would write.

此外,让我们假设您想继续自己编写它.

That aside, let's assume you want to go ahead and write it yourself anyway.

文件就像一个长字节数组.如果要增加或减少一行的长度,它将影响文件其余部分中每个字节的位置.结果可能比原始结果更短(或更长时间).由于结果可能会更短,因此就地修改文件是个坏主意.

A file is just like a long array of bytes. If you want to increase or decrease the length of one line, it affects the position of every byte in the rest of the file. The result can be shorter (or longer) than the original. As the result can be shorter, modifying the file in place is a bad idea.

以下伪代码说明了一种简单的方法:

The following pseudo-code illustrates a simple approach:

open original file
open output file
allocate a line buffer that is large enough
read a line from the original file
do
  return an error if the buffer is too small
  manipulate the line
  write the manipulated line to the output file
  read a line from the original file
loop until read returns nothing

sed更加智能.我曾经看到有关sed的工作原理的解释,但是我的Google业力似乎找不到它.

sed does it much smarter. I once saw an explanation on how sed works, but my google karma can't seem to find it.

修改: 使用sed的方法:

How to do it using sed:

 sed -e 's/.*\#.*/heet/g' myfile.txt

sed的s或替代命令可以将一个字符串或正则表达式替换为另一字符串.

The s, or substitute, command of sed can replace one string, or regular expression, with another string.

以上命令解释为:

heet替换其中任何具有#的行.最后的g告诉sed全局执行此操作,即在整个文件中执行此操作.

replace any line that has a # somewhere in it with heet. The final g tells sed to do this globally, i.e. in the entire file.

Edit2: 缺省情况下,sed写入标准输出. 要重写文件,您应该将输出重定向到文件,然后重命名. 在Linux中,请执行以下操作(您可以使用system从C运行命令行内容):

By default, sed writes to standard output. To rewrite the file you should redirect the output to a file and then rename it. In linux, do the following (you can run command line stuff from C with system):

sed -e 's/.*\#.*/heet/g' myfile.txt > temp_file123.txt
rm myfile.txt
mv temp_file123.txt myfile.txt

来自C:

system("sed -e 's/.*\#.*/heet/g' myfile.txt > temp_file123.txt");
system("rm myfile.txt");
system("mv temp_file123.txt myfile.txt");

如果只想调用system来完成此操作,请将所有命令行内容放入Shell脚本中.

If you want to do it with just one call to system, put all the command line stuff in a shell script.