2016-03-28 26 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