开发者

Parse IRC PRIVMSG in C

开发者 https://www.devze.com 2023-03-09 06:20 出处:网络
I am quite new to C (I am more used to C++) and I am trying to create an IRC Bot. I am currently开发者_StackOverflow struggling to find the correct string parsing functions to parse this line:

I am quite new to C (I am more used to C++) and I am trying to create an IRC Bot. I am currently开发者_StackOverflow struggling to find the correct string parsing functions to parse this line:

:nick!~username@server PRIVMSG #channel :message (could contain the word PRIVMSG)

So, I am asking if anyone could show me what functions I would use to split up this line into:

  • nick
  • username
  • server
  • channel
  • message

Thanks for any help!


I'd probably use sscanf. Something on this general order seems to be a reasonable starting point:

char nick[32], user[32], server[32], channel[32], body[256];

sscanf(buffer, ":%31[^!]!~%31[^@]@%31s PRIVMSG #%31s :%255[^\n]", 
                 nick,     user, server,       channel, body);


Considering that all this is in a char[] buffer that you can write onto (i.e., the contents will be overwritten), you can do something like:

char *nick, *username, *server, *command, *channel, *message;

nick     = strtok(buffer+1, "!");
username = strtok(NULL, "@");
server   = strtok(NULL, " ");
command  = strtok(NULL, " ");
channel  = strtok(NULL, " ");
message  = strtok(NULL, "");

You need to add some error checking to the above code, since any call to strtok() may return NULL if no more tokens are found. You could also use some more elaborate parsing, or sscanf().

Read the pages about strtok(3) and sscanf(3).

0

精彩评论

暂无评论...
验证码 换一张
取 消