Search code examples
cregexgccscanfstdio

sscanf with colon delimeter


I'm a newbie to C Programming. I want to extract the values out of the input buffer string. I saw a couple of examples for sscanf and it works with space delimiter but it doesn't work with colons or comma.

I tried to use some regex in sscanf but still doesn't seems to work.

#include <stdio.h>

int main() {

char buffer[] = "T:192.164.7.1:22:user:pass:empty:test.txt";
char cmdChar;
char ipAddress[100];
int port;
char username[100];
char password[100];
char folder[100];
char fileName[100];
char fileExtension[100];

sscanf(buffer, "%1c:%[^:]%d:%s:%s:%s:%s.%s", cmdChar, ipAddress, &port, username, password, folder, fileName, fileExtension);
printf("%c \n\n", cmdChar);

}

Tried to print the first character cmdChar but it returns as NULL. Can someone point me out what am I doing wrong. Thanks!


Solution

  • I can see a couple of problems with your format:

    • "%[^:]%d" - The first part will read until it hits the colon, but it will not read the colon itself, which means the following integer will not be read correctly and the rest of the string will be parsed incorrectly (if at all). You need "%[^:]:%d".

    • "%s.%s" for the string "test.txt". The %s format reads a space delimited string, which means the first "%s" there will read the whole "test.txt" into fileName. If you want to split into name and suffix you need to use the %[ format as int "%[^.].%s".

    And as mentioned in a comment, you need to pass a pointer to cmdChar.