簡體   English   中英

在C中使用strtok從配置中解析字符串

[英]parsing string off a configuration using strtok in C

在配置文件中,我有與此類似的條目:

filepath = c:\\ Program Files \\一些值

路徑可以包含空格且該字符串上沒有引號的位置。 我試着用strtok解析它:

char *option;
char *value;

value = strtok(line, " =");
strcpy(option, value);
value = strtok(NULL, " =");

其中line是我正在從文件中讀取的行,option將包含等號(文件路徑)的左側,value將包含右側(c:\\ program files \\ some value)。 我知道,這是糟糕的編碼,但是我還沒有發現更好的東西。 對不起...在任何情況下,對於右側沒有空格的那些選項,它都很好用,但是對於那些包含空格的選項,它只返回字符串直到第一個空格為止:c:\\ Program。

還有其他方法嗎?

代碼受到贊賞。 傑西卡(Jessica)

刪除定界符中的空間:

value = strtok(line, "=");

此處:strtok(line,“ =”)

您是說要在空間AND =上拆分。 浪費空間並根據需要調整結果。

您可以使用strtok_r() ,並使用它為字符串的其余部分提供的指針。

char *rightside;
char *leftside;

leftside = strtok_r(line, "=", &rightside);

請注意,這將浪費您的“行”緩沖區,但是通常無論如何您只要向其中讀取新數據就沒什么大不了的。

使用sscanf()

char * conf = "filepath = c:\\Program Files\\some value";
char key[20];
char value[40];
sscanf(conf, "%s = %40c", key, value);
printf("key: %s value: %s\n", key, value); 

應該這樣做:

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

#define INPUT_FILE "test.txt"
#define BUF_SIZE 1024
#define SEP " = "

#define CHECK(x) \
    do { \
        if (!(x)) { \
            fprintf(stderr, "%s:%d: ", __func__, __LINE__); \
            perror(#x); \
            exit(-1); \
        } \
    } while (0) \

void trim(char *s) {
    // Trim spaces and tabs from beginning:
    int i = 0, j;
    while((s[i]==' ') || (s[i]=='\t')) {
        i++;
    }
    if(i > 0) {
        for(j = 0; j < strlen(s); j++) {
            s[j] = s[j+i];
        }
    s[j] = '\0';
    }

    // Trim spaces and tabs from end:
    i = strlen(s) - 1;
    while((s[i]==' ') || (s[i]=='\t') || (s[i]=='\r')  || (s[i]=='\n')) {
        i--;
    }
    if(i < (strlen(s) - 1)) {
        s[i+1] = '\0';
    }
}

int main() {
    FILE *f;
    char line[BUF_SIZE + 1];
    char *opt, *val;

    line[BUF_SIZE] = '\0';

    f = fopen(INPUT_FILE, "rt");
    CHECK(f != NULL);

    while (NULL != fgets(line, sizeof(line), f)) {
        printf("%s", line);

        opt = strstr(line, SEP);
        if (!opt) {
            continue;
        }

        *opt = '\0';
        val = opt + strlen(SEP);
        opt = line;

        trim(opt);
        trim(val);

        printf("opt=<%s> val=<%s>\n", opt, val);
    }
    fclose (f);

    return 0;
}

trim功能是從這里獲取的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM