我想使用 C 语言使用 heet
更改文本文件中包含 #
符号的行。
我已经尝试过这种方式,但它并没有彻底工作,它只是替换字符并覆盖整个字符串,就像我想要的那样。
还有其他技巧可以从文件中删除或删除整行吗?所以,我们可以轻松地替换它。
myfile.txt: (执行前)
Joy
#Smith
Lee
Sara#
Priyanka
#Addy
代码:
#include <stdio.h>
#include <string.h>
int main() {
FILE *pFile;
fpos_t pos1, pos2;
int line = 0;
char buf[68]
char *p;
char temp[10] = "heet";
pFile = fopen("myfile.txt", "r+");
printf("changes are made in this lines:\t");
while (!feof(pFile)) {
++line;
fgetpos(pFile, &pos1);
if (fgets(buf, 68, pFile) == NULL)
break;
fgetpos(pFile, &pos2);
p = strchr(buf, '#');
if (p != NULL) {
printf("%d, " , line);
fsetpos(pFile, &pos1);
fputs(temp, pFile);
}
fsetpos(pFile, &pos2);
}
fclose(pFile);
return 0;
}
myfile.txt: (执行后)
Joy
heetth
Lee
heet#
Priyanka
heety
输出:
changes are made in this lines: 2, 4, 6,
myfile.txt: (我想获取)
Joy
heet
Lee
heet
Priyanka
heet
最佳答案
做你想做的事情的最好方法是使用像 sed 这样的实用程序。与您(或我)编写的任何内容相比,它速度更快,占用的内存更少。
除此之外,我们假设您无论如何都想自己编写它。
文件就像一个长字节数组。如果要增加或减少一行的长度,它会影响文件其余部分中每个字节的位置。结果可能比原始结果更短(或更长)。由于结果可能会更短,因此就地修改文件不是一个好主意。
以下伪代码说明了一种简单的方法:
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 karma 似乎找不到它。
编辑: 如何使用 sed 做到这一点:
sed -e 's/.*\#.*/heet/g' myfile.txt
sed 的 s(或替换)命令可以将一个字符串或正则表达式替换为另一个字符串。
上面的命令解释为:
将其中包含 #
的任何行替换为 heet
。最后的 g 告诉 sed 在全局范围内(即在整个文件中)执行此操作。
编辑2:
默认情况下,sed 写入标准输出。
要重写文件,您应该将输出重定向到文件,然后重命名它。
在 Linux 中,执行以下操作(您可以使用 system
从 C 运行命令行):
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 脚本中。
关于c - 使用 C 替换文本文件中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33231505/