dakatk dakatk - 1 year ago 136
C Question

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:


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

I should mention I have only a very basic grasp of how delimiters work in
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!

Answer Source

%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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download