简体   繁体   English

使用fscanf检测带引号的字符串

[英]Detect quoted strings with fscanf

I want to read in C the content of a file like this: 我想用C读取这样的文件内容:

foo="bar"
alice="bob"
fruit="pineapple"

And I am interested in the specific value associated with the key alice , but without the surrounding quotes. 我对与密钥alice关联的特定值感兴趣,但是没有周围的引号。 So, I want bob . 所以,我想要鲍勃

So, I've written something like this 所以,我写了这样的东西

EDIT: Added printf of key/value 编辑:添加了键/值的printf

char key[20];
char value[20];
char output[20];

memset(key, 0, 20);
memset(value, 0, 20);

while(fscanf(fd, "%19[^=]=\"%19[^\"]\"", key, value) != EOF) {

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

    if (strcmp(key, "alice") == 0) {
      memset(output, 0, 20);
      strncpy(output, value, 20);
      break;
    }

    memset(key, 0, 20);
    memset(value, 0, 20);
}

The problem is the strcmp never returns 0. So, the comparation between any key and "alice" is always false. 问题是strcmp永远不会返回0。因此,任何键和“ alice”之间的比较总是错误的。 And I'm getting this output: 我得到以下输出:

foo=bar
alice=bob
fruit=pinneaple
=pineapple

Also tested the length of each key, by strlen, and it's correct. 还测试了每个键的长度,以strlen表示,这是正确的。 Apart from the last line of rubish, I get what I expect. 除了最后一行,我得到了我所期望的。 So, I don't really understand... 所以,我不太了解...

Is there any obvious error here? 这里有明显的错误吗? I'm trying to debug the code, but I'm working with a target system very limited (openwrt), and I don't have access to gdb (actually, the code is cross-compiled in another machine, because my target one doesn't even have a compiler). 我正在尝试调试代码,但是我使用的目标系统非常有限(openwrt),并且我无法访问gdb(实际上,代码是在另一台计算机上交叉编译的,因为我的目标是甚至没有编译器)。

Any help is appreciated. 任何帮助表示赞赏。

Do not use scanf() for user input (even when it comes from a file). 不要将scanf()用于用户输入(即使它来自文件)。 Prefer fgets() . 更喜欢fgets()

Your immediate problem is with whitespace. 您的直接问题是空白。

The contents of the file include '\\n' . 文件的内容包括'\\n' The '\\n' are included in key . '\\n'包含在key

If you want to keep using fscanf() try adding some spaces inside the conversion string: 如果要继续使用fscanf()尝试在转换字符串中添加一些空格:

while (fscanf(fd, " %19[^=]= \"%19[^\"]\"", key, value) == 2) /* ... */;
//                 ^        ^ (2nd one isn't as important)

Also notice I changed the condition. 另请注意,我更改了条件。 Rather than testing against EOF , test for a return value of 2 . 而不是根据EOF测试,而是测试返回值为2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM