开发者

Parse IRC PRIVMSG in C

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜