0

到目前为止,我已经习惯了编写 eBPF 代码,并且希望避免在我的 BPF 文本中使用指针,因为从中获得正确的输出非常困难。由于所有示例代码都需要指针,因此使用 strtok() 似乎是不可能的。我还想在将来将其扩展为 CSV 文件,因为这对我来说是一种练习方式。我能够在这里找到另一个用户的代码,但由于一个指针,它给了我一个密件抄送终端错误。

char str[256];
bpf_probe_read_user(&str, sizeof(str), (void *)PT_REGS_RC(ctx));
char token[] = strtok(str, ",");

char input[] ="first second third forth";
char delimiter[] = " ";
char firstWord, *secondWord, *remainder, *context;

int inputLength = strlen(input);
char *inputCopy = (char*) calloc(inputLength + 1, sizeof(char));
strncpy(inputCopy, input, inputLength);

str = strtok_r (inputCopy, delimiter, &context);
secondWord = strtok_r (NULL, delimiter, &context);
remainder = context;

getchar();
free(inputCopy);
4

1 回答 1

-1

指针很强大,您将无法长时间避免它们。您花在学习它们上的时间绝对值得。

这是一个例子:

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

/**
    Extracts the word with the index "n" in the string "str".
    Words are delimited by a blank space or the end of the string.
}*/
char *getWord(char *str, int n)
{
    int words = 0;
    int length = 0;
    int beginIndex = 0;
    int endIndex = 0;
    char currentchar;
    while ((currentchar = str[endIndex++]) != '\0')
    {
        if (currentchar == ' ')
        {
            if (n == words)
                break;
            if (length > 0)
                words++;
            length = 0;
            beginIndex = endIndex;
            continue;
        }
        length++;
    }
    
    if (n == words)
    {
        char *result = malloc(sizeof(char) * length + 1);
        if (result == NULL)
        {
            printf("Error while allocating memory!\n");
            exit(1);
        }
        memcpy(result, str + beginIndex, length);
        result[length] = '\0';
        return result;
    }else
        return NULL;
}

您可以轻松使用该功能:

int main(int argc, char *argv[])
{
    char string[] = "Pointers are cool!";
    char *word = getWord(string, 2);
    printf("The third word is: '%s'\n", word);
    free(word); //Don't forget to de-allocate the memory!
    return 0;
}
于 2021-05-30T02:49:58.533 回答