如何处理 Unix 管道
如何在 C++ 代码中从 shell 重定向获取文件名?即./MyProgram < myfile ,我想逐行获取 myfile 作为文件名及其内容。
**编辑:我设法从文件中获取输入。感谢您的帮助。但是,在循环遍历文件内容后,我想用 cin 保留用户输入。是这样的:
while (true)
{
if (cin.eof() == false)
{
getline(cin, line);
cout << line;
}else{
cin >> choice;
}
}
How do I get the filename from redirection from the shell in my C++ code? i.e. ./MyProgram < myfile , I want to get myfile as the filename and its content line by line.
**Edit: I managed to get the input from file. Thanks for the help. However, after the looping through the file content, I want to keep user input with cin. It's like this:
while (true)
{
if (cin.eof() == false)
{
getline(cin, line);
cout << line;
}else{
cin >> choice;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不能(至少不能便携)。此信息不会提供给程序。相反,您可以通过从标准输入读取来访问
myfile
中的数据(在您的示例中)。例如,您可以使用 C++ 的 getline 和cin
作为第一个参数。You can't (at least not portably). This information is not provided to the program. Instead, you can access the data from
myfile
(in your example) by reading from standard input. E.g., you can use C++'s getline withcin
as the first parameter.根据 shell,您可能继承了代表实际文件或管道的描述符。如果它是一个实际的管道(即 fifo),那么这个名称就没有多大意义。但你可以在 linux 上得到这个名字(在 Windows 上也可以得到这个名字,但听起来你对此不感兴趣)。
请参阅在 C 中从文件描述符获取文件名
Depending on the shell, you may have inherited a descriptor representing an actual file or a pipe. If it's an actual pipe (i.e. fifo), the name won't mean much. But you can get the name on linux (and on Windows, but it doesn't sound like you're interested in that).
See Getting Filename from file descriptor in C