用另一个替换字符串

时间:2012-04-25 04:25:34

标签: c

我只是不确定为什么我的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 个答案:

答案 0 :(得分:5)

您已在r中打开文件,即读取模式并尝试写入。

同样在纠正之后,请注意,替换的单词和要替换的单词必须具有相同的大小, 如果要替换文件 。否则,您最终将覆盖其他数据。并且您需要使用fseek之类的函数来重新定位内部文件指针,因为fp

fscanf会向前移动