2016-03-28 69 views
1

在一个文件中我有几行,像这样:在特定行文件替换词,用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有,但“不完整”的文本仍然需要

+0

在C中没有真正的“替换”功能超过in.txt上面移动它,你需要覆盖所有下面的话。 – moeCake

+1

您应该从原始文件读取,转换,写入临时文件,然后将临时文件重命名为原始文件。覆盖也可以,但是在更换之后需要移动内容时,逻辑会有点混乱。 – Hang

回答

2

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

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

例如:

#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); 
} 

上面的代码应该给你一个什么样的介入了一些想法。一旦你已经out.txt保存,您可以使用标准的C函数rename(),例如:

rename("out.txt", "in.txt"); 
+0

'sscanf(lineBuffer,“程序在%9s是不完整的”,程序)'有'不完整'的印象''是重要的。 'sscanf(lineBuffer,“程序在%9s,程序)'也可以。 – chux

+0

'sscanf()'返回1,一旦有东西被扫描到'procedure'中,无论输入的其余部分是否匹配'“不完整”'' – chux

+0

@chux:好点! – dreamlax