我想使用C 更改包含#文本文件中的符号的行heet.
我已经尝试过这种方式,但它没有彻底运行,它只是替换字符和覆盖而不是整个字符串,就像我想要的那样.
还有其他技巧可以从文件中删除或删除整行吗?所以,我们可以轻松地取代它.
myfile.txt :( 执行前)
Joy
#Smith
Lee
Sara#
Priyanka
#Addy
Run Code Online (Sandbox Code Playgroud)
码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
myfile.txt :( 执行后)
Joy
heetth
Lee
heet#
Priyanka
heety
Run Code Online (Sandbox Code Playgroud)
输出:
changes are made in this lines: 2, 4, 6,
Run Code Online (Sandbox Code Playgroud)
myfile.txt :( 我想得到)
Joy
heet
Lee
heet
Priyanka
heet
Run Code Online (Sandbox Code Playgroud)
做你想做的最好的方法是使用像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
Run Code Online (Sandbox Code Playgroud)
sed做得更聪明.我曾经看过关于sed如何工作的解释,但我的谷歌业力似乎无法找到它.
编辑: 如何使用sed:
sed -e 's/.*\#.*/heet/g' myfile.txt
Run Code Online (Sandbox Code Playgroud)
s或者替换命令sed可以用另一个字符串替换一个字符串或正则表达式.
上面的命令被解释为:
替换任何具有其中#某个位置的行heet.最后的g告诉sed全局,即在整个文件中.
Edit2:
默认情况下,sed写入标准输出.要重写文件,您应该将输出重定向到文件,然后重命名它.在linux中,执行以下操作(您可以从C运行命令行内容system):
sed -e 's/.*\#.*/heet/g' myfile.txt > temp_file123.txt
rm myfile.txt
mv temp_file123.txt myfile.txt
Run Code Online (Sandbox Code Playgroud)
来自C:
system("sed -e 's/.*\#.*/heet/g' myfile.txt > temp_file123.txt");
system("rm myfile.txt");
system("mv temp_file123.txt myfile.txt");
Run Code Online (Sandbox Code Playgroud)
如果只想调用一次system,请将所有命令行内容放在shell脚本中.
您可能应该像对待 UNIX 实用程序一样对待输入/输出,并通过读取整个输入并写入整个输出来替换该行,就像sedwill 或其他东西一样。就地编辑该行会很痛苦,因为您需要将以下文本“向下”移动才能使其正常工作。