Your pointers are uninitialized. Reading them is undefined in C. You can use arrays (if you know the maximal lengths at compile-time) or allocate memory with malloc
.
Read the *scanf
documentation carefully, these functions are a little tricky.
"%s=%s"
cannot match, %s
consumes all =
signs so the following =
is always a matching failure (the next character after %s
is always a whitespace or EOF).
When reading strings, always use a maximum field width (in some cases, it can be omitted safely, but only for sscanf
). Unfortunately, you have to hard-code that value (or build up the format string at run-time, but I wouldn’t advise you to do so).
I'm not sure what the '
in the scan sets are supposed to do, %[^'=']
is equivalent to %[^'=]
and matches everything but '
and =
. You’ve probably meant %[^=]
.
Every white-space character in the format string (outside a scan set) is treated equally as "skip any white-space", that is, a space (
) is the same as a newline. The whole format string is equivalent to
"%[^'=]=%[^'\n] " // Note the space at the end
To match a literal newline, you need to use a scanset (with a length).
Always check the return value of *scanf
(also for fopen
and any other function which can fail).
char key[64]; // Or whatever is appropriate for you,
char value[64]; // remember the 0-terminator needs one byte
FILE *file = fopen("./file", "r");
if(!file) {
perror("./file");
exit(1);
}
for(;;) {
int e = fscanf(file, "%63[^=]=%63[^\n]%1[\n]", key, value, (char[2]){ 0 });
if(e == -1) {
if(ferror(file)) {
perror("reading from ./file");
// handle read error
} else { // EOF reached on first character of line
break;
}
} else if(e < 3) {
// handle invalid input
} else {
printf("key:%s value:%s\n", key, value);
}
}
Alternatively, you could use assignment-suppression for the last newline as in "%63[^=]=%63[^\n]%*1[\n]"
and omit the last argument to fscanf
. By doing so, you can no longer detect if the last line ended in a newline.