C: File parsing without losing white space
-
25-05-2021 - |
题
I am parsing a file for particular keyword matching by C program, here is my sample code...
#include <stdio.h>
int main() {
FILE *infile = fopen("Somefile.txt", "r");
char buffer[256];
char value[128];
while (fgets(buffer, sizeof(buffer), infile))
if (1 == sscanf(buffer, " x = %s", value))
printf("Value = %s\n", value);
return 0;
}
Somefile.txt
some junk
#a comment
a = 1 ; a couple other variables.
b = 2
x = 3
x = 4
x=5
x = Hi hello
Output:
Value = 3
Value = 4
Value = 5
Value = Hi
Problem : when x contain the value like "Hi Hello", then it just parsing "Hi" only, I want to parse whole value of x without loosing space.
please suggest me solution for it.
Thanks.
解决方案
In this line of your code:
if (1 == sscanf(buffer, " x = %s", value))
%s
means to read in one word.
If you want to read in the rest of the line, use %[^\n]s
like this:
if (1 == sscanf(buffer, " x = %[^\n]s", value))
其他提示
The first thing to do is back off on sscanf. If you read the man page, scanf treats spaces as specifications that say "you'll have some white space here, it's not important." Then other characters are specifications for literals. The effect is that that format spec is something like "any amount of while space, then an x, then more white space, then an '=', then more white space, then a string, and now return the string."
What you're really trying to do here is some lightweight parsing. You'll probably do better to read each line and scan it with a simple finite state machine, ie,
while not end of file
while not end of line
get next character
if char == ";" -- comment
break
if char is a letter
parse an assignment
and so on.