#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垃圾等我很好奇,如果有人能引导我的原因,谢谢你。
答案 0 :(得分:1)
假设单词的长度相同(如果不是,则会有更多问题):
假设您有一个4个字符的单词:
fseek (file, (-(long)len), SEEK_CUR);
将返回到位置0(4-4),fputc(charray[k],file);
将更新到位置1,然后再返回4,这是一个错误但是因为你没有检查来自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中的类似段落):
当使用更新模式打开文件时('+'作为mode参数中的第二个或第三个字符),可以在关联的流上执行输入和输出。但是,如果没有对fflush函数或文件定位功能(fseek,fsetpos或rewind)的干扰调用,输入可能不会直接跟随输入,并且输入可能不会直接跟随输出而没有对文件定位的干预调用函数,除非输入操作遇到文件结尾。
在读写之间你已经有了fseek,所以这不是问题