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

标签 c file

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

相关文章:

file - hadoop fs -text vs hadoop fs -cat vs hadoop fs -get

使用ImageIO打开图像后的Java文件操作

c - 重定向 execvp 路径

c - 将指向数组的指针传递给另一个函数 C

c - 此代码是否 ungetch() '\n' ?

php - move_uploaded_file 返回 true 但文件未出现在文件夹中

c - 将文件读入 2d 字符数组适用于 500 行,但不适用于 50,000 行

c - 函数 fscanf 首次使用后使应用程序崩溃

c - 递归在这里如何工作?(代码下方)

C++,如果我需要它,我是否应该#include *和*它包含的其他东西?