I need to create a search program in C language, that can parse the text file and find the keyword x=”value”. then I want to create a list of value items into array. Currently I am using fscanf approach, here is my code snippet.
fscanf(fp, "%s", buf);
if !strcmp(buf, "x")
{
fscanf(fp, "%s", buf);
if ( ! strcmp(buf, "="))
fscanf(fp, "%s", buf);
else
printf("\n Not a valid format");
}
I don’t want to use fscanf, Is there any other approach for my requirement??
Thanks.
There are other approaches (e.g., you could use Flex), but I think slightly better use of
sscanfwould make the most sense:Edit: The basic idea here is pretty simple. We start by reading a whole like with
fgets. We then usesscanfto try to matchx=<whatever>in that line. If we find it, we have the value we care about. If we didn’t find it, sscanf will return 0, since it returns the number of items it converted — and if it doesn’t match thex=we specified, it won’t convert anything, so sscanf will return 0, and we know that line didn’t match.Edit 2: Here’s a small demo program that reads data from a file, and prints out the values for lines that follow the form
x=<whatever>, with spaces allowed before and after thexand the=:I tested it with this as input:
The result I got was: