在文件

时间:2019-04-03 09:57:17

标签: c++ c file

我的代码是接受命令行args中的值并搜索字符串,并替换在每行中的关键字之间用分隔符分隔的行中找到的字符串之后的下一个字符。

基本上,在从缓冲区字符串中找到与该字符串的文件指针位置相对应的字符位置之后,然后在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]);
                }

如果有人对此表示感谢,将不胜感激

1 个答案:

答案 0 :(得分:0)

对我来说还不是很清楚,您正在那里尝试什么,但是如果这不是您所需要的,请告诉我:

#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

我不是在文件中搜索,因为您需要一种修改缓冲区的方法,所以我将让您在此完成其余的工作。

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