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

int main ( int argc, char *argv[] )
{
    if ( argc != 4 ) /* argc should be 4 for correct execution */
    {
        /* 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;int count = 0;int i = 0;int k = 0;
            while  ( (fscanf( file, "%s", string ) ) != EOF )
            {
                len = strlen(string);
                count++;
                char charray[len+1];
                if(count == 1)
                {
                    for (i = 0; i < len; i++)
                    {
                        charray[i] = replaceWord[i];
                        printf("%c\n", charray[i]);
                    }
                }
                //printf("%c\n", charray[0]);
                printf( "%s\n", string );
                if(strcmp(string, wordReplace) == 0)
                {
                    for(k = 0; k < strlen(replaceWord); k++)
                    {
                         fseek (file, (-(long)len), SEEK_CUR);
                         fputc(charray[k],file);
                         //replaceWord++;
                    }
                    //strcpy(string, replaceWord);
                    //fprintf(file,"%s",replaceWord);
                    //fputs(string, file);
                    //printf("\n%d\n", len);
                }       
            }
            fclose( file );
        }
    }
    printf("\n");
    return 0;
}

此代码当前可以正确替换第一个单词,但是如果我想用替换单词覆盖多个单词,或者该单词出现在文本中的其他位置,它将无法正确更改它,并且会将其更改为 ram 垃圾等.我很好奇是否有人能告诉我一个感谢你的原因。

4

1 回答 1

1

假设单词的长度相同(如果不是,您还有很多问题):假设您有一个 4 个字符的单词: fseek (file, (-(long)len), SEEK_CUR);将返回位置 0 (4-4),fputc(charray[k],file);将更新到位置 1,然后返回 4 more 这是一个错误,但是由于您没有检查 fseek 的返回值,因此您不会知道这一点。此时算法不再起作用,因为您假定的文件位置都是错误的

编辑:

if(strcmp(string, wordReplace) == 0)
{
    fseek (file, (-(long)len), SEEK_CUR);
    for(k = 0; k < strlen(replaceWord); k++)
    {                         
        fputc(charray[k],file);
    }

} 
fflush(file); //you need to flush the file since you are switching from write to read

编辑 2:刷新原因:来自 4.5.9.2 ANSI C,C99 7.19.5.3 中的类似段落):

当以更新模式(模式参数中的第二个或第三个字符为“+”)打开文件时,可以在关联的流上执行输入和输出。但是,如果没有对 fflush 函数或文件定位函数( fseek 、 fsetpos 或 rewind )的介入调用,输出可能不会直接跟随输入,并且如果没有对文件定位的介入调用,输入可能不会直接跟随输出函数,除非输入操作遇到文件结尾。

在读写之间你已经有了 fseek 所以这不是问题

于 2012-04-26T15:22:58.060 回答