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;
}
4

1 に答える 1

5

ファイルを読み取りモードで開き、r書き込みを試みました。

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

于 2012-04-25T04:28:54.890 に答える