|
最近要编一个程序,简单地模仿Linux/Unix下的cat
以下是我的两个版本
- //h.cpp
- #include <iostream>
- #include <fstream>
- #include <string.h>
-
- using namespace std;
-
- inline void display(istream& istrm);
-
- int main(int argc, char* argv[])
- {
- if (argc==1) display(cin);
- for(int i=1; i<argc; ++i)
- {
- if (strcmp(argv[i], "-")==0)
- {
- display(cin);
- continue;
- }
- ifstream in(argv[i]);
- if (!in)
- {
- cerr<<("%s", argv[0])<<": "<<("%s", argv[i])
- <<": No such a file or directory!"<<endl;
- continue;
- }
- display(in);
- }
- return 0;
- }
-
- inline void display(istream& istrm)
- {
- char buf;
- while(istrm.get(buf)) cout.put(buf);
- }
复制代码
-------------------------------------------
- //i.cpp
- #include <iostream>
- #include <fstream>
- #include <iterator>
- #include <string.h>
-
- using namespace std;
-
- inline void display(istream& istrm);
-
- int main(int argc, char* argv[])
- {
- if (argc==1) display(cin);
- for(int i=1; i<argc; ++i)
- {
- if (strcmp(argv[i], "-")==0)
- {
- display(cin);
- continue;
- }
- ifstream in(argv[i]);
- if (!in)
- {
- cerr<<("%s", argv[0])<<": "<<("%s", argv[i])
- <<": No such a file or directory!"<<endl;
- continue;
- }
- display(in);
- }
- return 0;
- }
-
- inline void display(istream& istrm)
- {
- istreambuf_iterator<char> inpos(istrm);
- istreambuf_iterator<char> endpos;
- ostreambuf_iterator<char> outpos(cout);
- while(inpos!=endpos)
- {
- *outpos=*inpos;
- ++inpos;
- ++outpos;
- }
- }
复制代码
本来h.cpp已经工作的不错了,但存在一个bug
对于cat命令来说,在控制台下输入cat - -这个命令时,cat将显示你从控制台输入的东西,要按Ctrl+D先退出第一个'-',再按一次Ctrl+D退出第二个
但我的h.cpp中,你只要按了一次Ctrl+D,就全部退出了
于是我将h.cpp改为i.cpp
在我的Linux FC3下,i.cpp不存在那个bug,但是在学校的SunOS 5.8下,那个bug又出现了
我的问题是,怎样才能彻底地去掉这个bug? |
|