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

您已经在rie 读取模式下打开了文件并尝试对其进行写入。

同样在更正之后,请注意,如果要替换文件,替换的单词和要替换的单词的大小必须相同。否则,您最终将覆盖其他数据。并且您需要使用诸如fseek重新定位内部文件指针之类的功能,因为fp之后会向前移动fscanf

于 2012-04-25T04:28:54.890 回答