gpt4 book ai didi

c - 用另一个替换字符串

转载 作者:太空宇宙 更新时间:2023-11-04 01:12:05 24 4
gpt4 key购买 nike

我只是不确定为什么我的 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;
}

最佳答案

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

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

之后向前移动

关于c - 用另一个替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10309354/

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