2012-04-25 228 views
1

我只是不確定爲什麼我的replaceWord沒有進入文件,我已經使用了所有的註釋等,等等。我只是試圖用從命令行參數收到的文本替換。我知道我可能離我很遠,我只是尋找一個相對簡單的方法來做到這一點。用另一個替換字符串

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int main (int argc, char *argv[]) 
{ 
if (argc != 4) /* argc should be 2 for correct execution */ 
    { 
     /* We print argv[0] assuming it is the program name */ 
     printf("usage: %s filename\n", argv[0]); 
    } 
    else 
    { 
     // We assume argv[1] is a filename to open 
     char* wordReplace = argv[1]; 
     char* replaceWord = argv[2]; 
     FILE *file = fopen(argv[3], "r"); 
     /* fopen returns 0, the NULL pointer, on failure */ 
     if (file == 0) 
     { 
      printf("Could not open file\n"); 
     } 
     else 
     { 
      char string[100]; 
      int len = 0; 
      /* read one character at a time from file, stopping at EOF, which 
       indicates the end of the file. Note that the idiom of "assign 
       to a variable, check the value" used below works because 
       the assignment statement evaluates to the value assigned. */ 
      while ((fscanf(file, "%s", string)) != EOF) 
      { 
       len = strlen(string); 
       printf("%s\n", string); 
       if(strcmp(string, wordReplace) == 0){ 
       //fseek (file, (-strlen(string) + 1), 1); 
       //fputc(*replaceWord,file); 
       //replaceWord++; 
       //strcpy(string, replaceWord); 
       fprintf(file,"%s",replaceWord); 
       fputs(replaceWord, file); 
       printf("\n%d\n", len); 
       } 
      } 
      fclose(file); 
     } 
     } 
    printf("\n"); 
    return 0; 
} 
+1

您已經以讀取模式打開文件。以讀寫模式打開文件,即「r +」。 – 2012-04-25 04:29:22

+0

寫入臨時文件;刪除原始文件;將臨時文件重命名爲原始文件 – BLUEPIXY 2012-04-25 07:55:53

回答

5

您已經打開文件r即讀取模式並嘗試寫入它。

而且糾正後,請注意,被替換的字和詞進行更換必須是相同的大小,如果要替換該文件在地方。否則你最終會覆蓋其他數據。並且您需要使用fseek等函數重新定位內部文件指針,因爲fp將在fscanf之後提前移動

+0

我已經取得了一些進展。使用這個當前的代碼,只有在第一個單詞是文本中的第一個單詞時,它纔會取代第一個單詞。但是,如果這個詞是其他任何地方的話。 printf(「%s \ n」,string); \t \t \t \t如果(的strcmp(字符串,wordReplace)== 0){ \t \t \t \t爲(K = 0; k thekevshow 2012-04-26 14:29:02

相關問題