【发布时间】:2023-01-18 22:53:18
【问题描述】:
下面是一个 C++ 小程序,它应该充当 cat linux binutil:它获取一个或多个输入,如命令行参数中详述(可能通过“-”指定标准输入)并将它们复制到标准输出。不幸的是,它显示了一种我无法理解的根本原因的意外行为......
根据以下命令
./ccat - test.text
我直接按了 CTRL-D,没有传递任何字符。我希望该程序无论如何都显示 test.txt 的内容,但相反,该程序退出时没有将任何更多字符传递到标准输出流。
关于我应该如何更正我的代码以在这种情况下具有正确行为的任何想法?我应该处理标准流的多个实例(cin、cout...)吗?如果是这样,您知道如何在 C++ 中实现这一点吗?
先感谢您。
/**** ccat.cpp ****/
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main(int argc, char **argv) {
if (argc <= 1) {
cout << cin.rdbuf();
} else {
vector<string> inputs;
for (int i=1; i<argc; ++i) inputs.push_back(argv[i]);
for (auto &in: inputs) {
if (in == "-" || in == "--") {
cout << cin.rdbuf();
}
else {
ifstream *fd = new ifstream(in);
if (!fd->is_open()) cerr << "Cannot open file \'" << in << "\'\n";
else cout << fd->rdbuf();
delete fd;
}
}
}
return 0;
}
我依次尝试了以下命令:
$ ./ccat > test.txt
Let's try this text.
I would expect a correct behaviour.
$ ./ccat - test.txt # I hit CTRL-D directly without passing any character first
$ ./ccat - test.txt
But when I add some characters before hitting CTRL-D... This works fine.
But when I add some characters before hitting CTRL-D... This works fine.
Let's try this text.
I would expect a correct behaviour.
如示例所示,我希望在两种情况(最后两个 shell 提示)中的任何一种情况下 test.txt 都显示在标准输出上,但只有当我首先通过标准输入注入字符时才会发生这种情况。直接按 CTRL-D 会使程序提前退出。
【问题讨论】:
-
不是你的(当前)问题:你不应该使用
new来创建ifstream->ifstream fd{in}; -
您在 Ctrl-D 之前按了 Enter 键来运行命令,对吗?