gpt4 book ai didi

c++ - 在文件中找到字符串后替换它旁边的字符

转载 作者:行者123 更新时间:2023-11-30 16:19:49 25 4
gpt4 key购买 nike

我的代码是接受来自命令行参数的值并搜索字符串并替换在每行中的关键字由分隔符分隔的行中找到的字符串后面的下一个字符。

基本上在从缓冲区字符串中找到与该字符串的文件指针位置相对应的字符位置后,然后更新 fp+X 处的字符。我想知道有什么办法可以做到吗?

我对 C++ 也很满意。

我有如下的 file.txt

FOO,val1=0,val2=0
BAR,val1=0,val2=0
TOO,val1=0,val2=0

命令行

#./a.out FOO val1 1

mycode.c

char        buffer[kKEYWORD_SIZE];
FILE* fd;

if ((fd = fopen(file.txt, "r+")) != NULL)
{
do
{
memset(buffer, 0x0, kKEYWORD_SIZE);
if (fgets(buffer, kKEYWORD_SIZE, fd) != NULL)
{
//storing the entire line into pointer to character array.
for (index = 0, token = strtok_r(buffer, sep, &last); token; token = strtok_r(NULL, sep, &last), index++)
strcpy(*(keyword + index), token);


// the first keyword found and search for 2nd keyword and replaces its value
if (strcmp(*(keyword + 0), key1) == 0)
{
if ( ( find = strstr(buffer, key2 )) != NULL )
{
// I want fp pointers to move it to find+5
fputs(fp,argv[3]);
}

如果有人对此有所了解,我们将不胜感激

最佳答案

嗯,我不太清楚,你在那里尝试什么,但如果这不是你需要的,请告诉我:

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

int findFOO( const char *const ptr, const char *const substr );
int search( const char *const src, const char *str );

size_t findOCC ( char *const src, const char *substr );

int main ( void )
{
char arr[] = "FOO,val1=0,val2=0" ;

printf("Before: %s\n", arr );

size_t len = findOCC( arr, "var1" );
arr[len] = '1';

printf("After: %s\n " , arr );

}

int findFOO( const char *const ptr, const char *const substr )
{
char *ret = strstr( ptr, substr );
if ( ret == NULL )
{
return 0;
}
return 1;
}


int search( const char *const src, const char *const str )
{
int i, j, firstOcc;
i = 0, j = 0;

while (src[i] != '\0')
{

while (src[i] != str[0] && src[i] != '\0')
i++;

if (src[i] == '\0')
return (-1);

firstOcc = i;

while (src[i] == str[j] && src[i] != '\0' && str[j] != '\0')
{
i++;
j++;
}

if (str[j] == '\0')
return ( firstOcc );
if (src[i] == '\0')
return (-1);

i = firstOcc + 1;
j = 0;
}
return 0;
}

size_t findOCC ( char *const src, const char *substr )
{
char buffer[strlen( src) + 1 ];
strcpy( buffer, src );
if ( findFOO ( src, "FOO" ) ) /// Search if there is a Line containing FOO
{

int ret = search( buffer, substr );
if ( ret ) /// found a Match
{
char *tmp = strtok( buffer, "=" );
return strlen( tmp ) + 1; /// return the index
}

}
return 0;
}

输出:

Before: FOO,val1=0,val2=0
After: FOO,val1=1,val2=0

我没有在文件中搜索,因为您需要一种方法来修改缓冲区,所以我会让您在这里完成其余的工作。

当然,这里需要进行很多错误检查,但我相信您可以弄清楚您需要做什么。

关于c++ - 在文件中找到字符串后替换它旁边的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55492293/

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