-2
char string[200]="ret=\"y\"  err=\"000\"";
    char stringg[50];
    char *arg;
    arg  = strstr (string, "ret");
    memcpy(stringg,arg+5,1);
    printf(stringg);

I want to copy value of "ret",above program gives the output but when value of ret changes i have to make changes in program. How to solve this issue

saurabh
  • 17
  • 3

1 Answers1

0

In your code, their is no need to give a limit to your array string. You can simply use:

const char string[] = "ret=\"y\"  err=\"000\"";

After finding the value of "ret" with strstr(), and checked that NULL was not returned, you can copy all the contents into a separate array or pointer, then stop copying when the first space is found. This would ensure that ret = "y" was copied. Once the space is found, terminate your array or pointer with a \0 terminator.

You can then use strchr(3) to find the position of the '=' character, and if it exists, assign the value after it into another variable. This variable will then contain the value after the equals sign.

Here is an example:

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

int main(void) {
    const char string[] = "ret=\"y\"  err=\"000\"";
    const char *key = "ret";
    const char equals = '=', space = ' ', quote = '"';
    char *start, *copy, *next, *value;
    size_t i;

    start = strstr(string, key);
    if (start != NULL) {
        copy = strdup(start);
        if (copy == NULL) {
            fprintf(stderr, "Failed to copy contents of string\n");
            exit(EXIT_FAILURE);
        }
        for (i = 0; start[i] != space && start[i] != '\0'; i++) {
            copy[i] = start[i];
        }
        copy[i] = '\0';

        next = strchr(copy, equals);
        if (next != NULL) {
            next++;
            if (*next == quote) {
                next++;
                next[strlen(next)-1] = '\0';
                value = next;
            }
        }

        printf("%s = %s\n", key, value);

        free(copy);
    }

    return 0;
}
RoadRunner
  • 25,803
  • 6
  • 42
  • 75