简体   繁体   中英

Using Delimiters for 'fscanf' in c

I am trying to read a file in C in a way that it would load simple variables and values. For example, let's say this is the text of the file:

a=100
b=hello
c=world

ow the idea would be to load each line of the file such that the string on the left of the equals sign would be the name of the variable, and the string on the right would be loaded in as the value. This is the code that would read the file in the way I described:

#include <stdio.h>

int main(void)
{
    FILE* f;
    f = fopen("test.txt", "r");

    char name[256];
    char value[256];

    while(fscanf(f, "%255[^=]=%255[^=]", name, value) == 2)
        printf("%s, %s\n", name, value);

    return 0;
}

But when I compile and run it, all I get as the output is:

a, 100
b

I should mention I have only a very basic grasp of how delimiters work in scanf or fscanf for the formatting strings. I have a feeling that's what's going wrong here, but I have yet to find or stumble upon a solution. Any help would be appreciated!

%255[^=] will read everything from the = on the first line to the = on the second line, since you didn't include newline as a delimiter. So it's setting name to "100\\nb" . The next fscanf() fails because there's no string before the = .

Use newline as your second delimiter rather than = , and put a space before the first format so it skips over whitespace before parsing each line.

while(fscanf(f, " %255[^=]=%255[^\n]", name, value) == 2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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