gpt4 book ai didi

c - 替换文本C语言中的字符串

转载 作者:行者123 更新时间:2023-11-30 15:57:41 25 4
gpt4 key购买 nike

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

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

最佳答案

假设单词的长度相同(如果不是,则还有很多问题):假设您有一个 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中的类似段落:

When a file is opened with update mode ('+' as the second or third character in the mode argument), both input and output may be performed on the associated stream. However, output may not be directly followed by input without an intervening call to the fflush function or to a file positioning function ( fseek , fsetpos , or rewind ), and input may not be directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end-of-file.

在读取和写入之间,您已经有了 fseek,所以这不是问题

关于c - 替换文本C语言中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10335963/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com