gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:09:09 27 4
gpt4 key购买 nike

我想使用 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/7736322/

27 4 0
文章推荐: html - 基于 Web 的 HTML 片段编辑器
文章推荐: java - 如何通过将字符串 'xxx' 作为参数传递给该方法来从该方法访问 R.string.xxx 资源?
文章推荐: javascript - 如何在用户放大和缩小页面时保持
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com