使用c替换特定行的文件中的单词

时间:2016-03-28 02:31:28

标签: c

在一个文件中我有几行如下:

The procedure at A1 is complete The procedure at B132 is incomplete The procedure at C45 is incomplete The procedure at D2 is complete

如果我知道我想更改第3行的程序,请转到X4534

The procedure at C45 is incompleteThe procedure at X4534 is incomplete

这样做的简单方法是什么?

我查看了fseek函数,我认为我可以循环直到达到所需的行,前进18个空格,fwrite那里但是“不完整”的文本仍然需要

1 个答案:

答案 0 :(得分:2)

对于这种类型的替换(要替换的字符串的长度和要替换它的字符串的长度不同),您通常需要从一个文件中读取,并将更改的数据写入另一个文件。 / p>

您可以逐行阅读该文件,然后使用sscanf()确定该行是否需要更换。

例如:

private void pdfViewer1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Control && e.KeyCode == Keys.P) //detect key ctrl+p
    {
        e.Handled = false;
        MessageBox.Show("This Document is Protected !", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
        return;
    }
    base.OnKeyDown(e);
}

上面的代码可以让您了解所涉及的内容。保存#include <string.h> #include <stdio.h> int main() { FILE *input = fopen("in.txt", "r"); FILE *output = fopen("out.txt", "w"); char target[] = "C45"; char replacement[] = "X4534"; char lineBuffer[100]; while (fgets(lineBuffer, sizeof lineBuffer, input) != NULL) { char procedure[10]; if (sscanf(lineBuffer, "The procedure at %9s", procedure) == 1) { if (strcmp(procedure, target) == 0) { // if we get here, then the line matched the format we're // looking for and we can therefore write our replacement // line instead. fprintf(output, "The procedure at %s is incomplete\n", replacement); continue; } } // if we get to this point, then the line didn't match the format // or the procedure didn't match the one we're looking for, so we // just output the line as it is. fputs(lineBuffer, output); } fclose(input); fclose(output); } 后,您可以使用标准C函数rename()将其移至out.txt的顶部,例如:

in.txt