Skip to content

Instantly share code, notes, and snippets.

@eliaskanelis
Created April 19, 2023 17:42
Show Gist options
  • Save eliaskanelis/fa5198ed62e795bb969f73d17c28e434 to your computer and use it in GitHub Desktop.
Save eliaskanelis/fa5198ed62e795bb969f73d17c28e434 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
char buffer[] ="\n\
source state,1\n\
source state,2\n\
source state,3\n\
source state,4\n\
\n\
address 192.168.1.2,4000,6\n\
address 192.168.99.1,4000,20\n\
address 192.168.99.2,4000,8\n\
address 172.16.30.50,8000,125\n\
address 172.16.30.51,9000,80\n\
";
static int parse(const char* name, const char* value)
{
int error = 0;
if( 0 == strncmp(name, "source", 6U) )
{
char name[11U];
char port[11U];
const int rv = sscanf(value, "%10[^,],%10s", name, port );
if(rv != 2)
{
error = 1;
}
if(error == 0)
{
printf("-------------------------\n");
printf("Name: %s\n", name);
printf("Port: %s\n", port);
}
}
else if( 0 == strncmp(name, "address", 7U) )
{
char ip_a[4U];
char ip_b[4U];
char ip_c[4U];
char ip_d[4U];
char port[11];
char id[11];
const int rv = sscanf(value, "%3[^.].%3[^.].%3[^.].%3[^,],%10[^,],%10s", ip_a, ip_b, ip_c, ip_d, port, id);
if(rv != 6)
{
error = 1;
}
if(error == 0)
{
printf("-------------------------\n");
printf("value: %s\n", value);
printf("ip: %s.%s.%s.%s\n", ip_a, ip_b, ip_c, ip_d);
printf("Port: %s\n", port);
printf("Id: %s\n", id);
}
}
else
{
printf("Not found\n");
error = 1;
}
return error;
}
int main()
{
int error = 0;
char* line = strtok(buffer, "\n");
while (line != NULL && error == 0)
{
char name[255];
char value[255];
const int rv = sscanf(line, "%255s%255s", name, value);
if(rv == 2)
{
error = parse(name, value);
}
line = strtok(NULL, "\n"); // get the next line
}
return error;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment