2012-04-25 45 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 +"でファイルを開いてください。 –

+0

一時ファイルを書き込む;元のファイルを削除する;一時ファイルの名前を元のファイルに変更してください – BLUEPIXY

答えて

5

rでファイルを開いて、書き込みモードにしました。

はまた、これを修正した後、置き換え単語と単語を交換することに注意してくださいあなたの場所にファイルを置き換えたい場合は、同じサイズでなければなりません。他のデータを上書きすることになります。また、fseekのような関数を使用して、内部ファイルポインタの位置を変更する必要があります。fscanf

+0

私はいくつかの進歩を遂げました。この現在のコードでは、テキストの最初の単語である場合にのみ、最初の単語を置き換えます。しかし、もしその言葉がどこにでもあるならば。 printf( "%s \ n"、文字列); \t \t \t \t IF(のstrcmp(文字列、wordReplace)== 0){ため \t \t \t \t(K = 0; K thekevshow

関連する問題