当数据成块进入时,最简单的获取线路的方法是什么?
我正在使用 win32 的 ReadFile 从子进程的管道中读取。这一次为我提供了字符块以及每个块的大小,但它们可能有也可能没有新行。我想逐行处理输出。最简单的方法是什么?
我考虑过将每个块附加到一个 string
中,最后使用 stringstream
逐行处理它,但我想这样做,因为数据是我想诀窍是,我应该如何以及在哪里检测新行结尾?如果在找不到分隔符时,streamreader
的 getline
没有返回任何内容...
I am using win32's ReadFile
to read from a child process's pipe. That gives me chunks of characters at a time and the size of each chunk, but they may or may not have new lines. I want to process the output line by line. What is the simplest way of doing so?
I thought about appending each chunk to a string
, and at the end, using a stringstream
to process it line by line, but I'd like to do this as data is coming in. I suppose the trick is, how and where should I detect the new line ending? If only streamreader
's getline
returned nothing when no delimiter is found...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
附加到字符串,直到遇到换行符或数据结尾。然后字符串中有一行,对其进行处理,清空字符串并重复。使用字符串的原因:您不知道一行可能有多长,并且字符串会根据需要为您进行重新分配等。
特殊情况:该行前面没有任何内容的数据结尾可能应该不是一行,被忽略。
干杯&嗯。
Append to a string until you encounter newline char or end of data. Then you have a line in the string, process it, empty string and repeat. Reason for using the string: that you don't know how long a line may be, and a string does the reallocation etc. for you as necessary.
Special case: end of data with nothing earlier on that line should probably be not-a-line, ignored.
Cheers & hth.
我能想到的是使用一个缓冲区来存储传入您的块,您通过 lpNumberOfBytesRead 知道大小,因此在每个块上检查它是否包含换行符,如果包含,则输出所有缓冲的字符,直到新行字符,然后开始缓冲,直到收到另一个包含新行字符的块,依此类推。
一些伪代码可能如下所示:
What I can think of is using a buffer where to store chunks coming to you, you know the size via lpNumberOfBytesRead, so on each chunk you check if it contains new line character/s and if it does, you output all the buffered characters till the new line character, then start buffering until you received another chunk with new line characters and so on.
Some pseudo code might look like:
您可以扩展 std::basic_streambuf 并实现 xsputn ,以便它将数据存储在内部缓冲区中,并检测换行符或执行您需要的任何处理。如果您只想处理完整的行,则在检测到时,您可以将缓冲区推送到 std::queue 直到换行符,然后从缓冲区中删除相应的部分。您还需要实现
overflow
。例如:注意:高度未经测试的代码。如果您发现问题,请告诉我,或者随时进行编辑。
You can extend
std::basic_streambuf
and implementxsputn
so it stores data in an internal buffer, and detect newlines or do whatever processing you need. If you want to process only complete lines, upon detection you can push the buffer to astd::queue
up to the newline, and erase the respective part from the buffer. You'll need to implementoverflow
too. For example:NOTE: highly untested code. Let me know if you find a problem, or feel free to edit.