c recv() read until newline occurs

后端 未结 2 800
太阳男子
太阳男子 2021-01-11 18:03

I\'m working on writing a IRC bot in C, and have ran into a snag.

In my main function, I create my socket and connect, all that happy stuff. Then I have a (almost) i

2条回答
  •  攒了一身酷
    2021-01-11 18:59

    TCP doesn't offer any sequencing of that sort. As @bdonlan already said you should implement something like:

    • Continuously recv from the socket into a buffer
    • On each recv, check if the bytes received contain an \n
    • If an \n use everything up to that point from the buffer (and clear it)

    I don't have a good feeling about this (I read somewhere that you shouldn't mix low-level I/O with stdio I/O) but you might be able to use fdopen.

    All you would need to do is

    • use fdopen(3) to associate your socket with a FILE *
    • use setvbuf to tell stdio that you want it line-buffered (_IOLBF) as opposed to the default block-buffered.

    At this point you should have effectively moved the work from your hands to stdio. Then you could go on using fgets and the like on the FILE *.

提交回复
热议问题