管道输入数据
我需要编写一个程序来处理来自文件或 shell 的输入(用于管道处理)。处理这个问题最有效的方法是什么?我本质上需要逐行读取输入,但输入可能是 shell 或文件中另一个程序的输出。
谢谢
I need to write a program that works with input from either a file or the shell (for pipeline processing). What is the most efficient way to deal with this? I essentially need to read the input line by line, but the input might be the output of another program from shell, or a file.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我找不到评论链接,所以发布答案。
正如 Eugen Constantin Dinca 所说,将输出通过管道或重定向到标准输入,因此您的程序需要做的就是从标准输入读取。
我不知道你提到的“逐行读取”是什么意思,比如ftp交互模式?如果是这样,程序中应该有一个循环,每次读取一行并等待下一个输入,直到给出终端信号。
编辑:
I can't find the comments link, so post an answer.
As Eugen Constantin Dinca said, pipe or redirect just output to the standard input, so what your program need to do is read from standard input.
I don't know what "read line by line" mean as you mentioned, something like ftp interactive mode? If that, there should be a loop in your program which read a line once a time and wait for the next input until you give the terminal signal.
Edit:
, in C 的 C 示例:
以下是来自 Echo All Palindromes 将其转换为 C++:编写接受
std::istream&
的函数(上面是回文
);从main()
函数传递std::cin
(用于标准输入,或“-”文件名)或ifstream
对象。在函数内使用
std::getline()
和给定的std::istream
对象来逐行读取输入(该函数不关心输入是否来自文件或标准输入)。Here's a C example from Echo All Palindromes, in C:
To adapt it to C++: write function (it is
palindromes
above) that acceptsstd::istream&
; pass it eitherstd::cin
(for standard input, or '-' filename) orifstream
objects from themain()
function.Use
std::getline()
with a givenstd::istream
object inside the function to read input line by line (the function doesn't care whether input is from a file or stdin).我认为它是您想要使用的命名管道。但据我所知,另一个程序必须将其输出写入命名管道(如果您有权访问该程序,则可以这样做),并且您的程序将从命名管道中读取。
希望这对您有帮助。
I think its a named pipe you want to work with. But from what I know the other program must write its output to the named pipe (If you have access to that program you can do that) and your program will read from the named pipe.
Hope this helps you.
我可能会误解这个问题,但我认为您希望您的程序能够像这样使用:
cat [some_file] | [您的程序]
或[您的程序] < [some_file]
。如果是这种情况,那么您只需要从标准输入(stdin/cin)读取数据,shell 将处理其余的事情。
如果您希望程序从标准输入或文件读取,您可以执行许多命令行实用程序的操作,即
有关实现上述内容的代码示例,请参阅这篇文章。
I might be misinterpreting the question but I think you want your program to be able to be used like this:
cat [some_file] | [your_program]
or[your program] < [some_file]
.If that's the case than you just need to read from the standard input (stdin/cin), the shell will take care of the rest.
If you want your program to either read from stdin or from a file you can do what a number of command line utils do, i.e. cat:
For a code sample implementing the above see this article.