繼承我可以從ifstream的繼承和讀取我的派生類像這樣的文件:從ifstream的
#include <iostream>
using namespace std;
const string usage_str = "Usage: extract <file>";
class File: public ifstream
{
public:
explicit File(const char *fname, openmode mode = in);
void extract(ostream& o);
};
File::File(const char *fname, openmode mode)
{
ifstream(fname, mode);
}
void File::extract(ostream& o)
{
char ch;
char buf[512];
int i = 0;
while (good()) {
getline(buf, sizeof(buf));
o<<buf;
i++;
}
cout<<"Done "<<i<<" times"<<endl;
}
void msg_exit(ostream& o, const string& msg, int exit_code)
{
o<<msg<<endl;
exit(exit_code);
}
int do_extract(int argc, char *argv[])
{
cout<<"Opening "<<argv[1]<<endl;
File f(argv[1]);
if (! f)
msg_exit(cerr, usage_str, 1);
f.extract(cout);
return 0;
}
int main(int argc, char *argv[])
{
if (argc < 2)
msg_exit(cout, usage_str, 0);
do_extract(argc, argv);
return 0;
}
我希望它讀取整個文件,但它讀取只是一個符號(這是不是第一次給定文件的符號)...
good()!!這是做什麼的? – DumbCoder
'ifstream(fname,mode)'應該被移動到一個初始化列表。您應該在嘗試讀取數據和使用它之間進行一些錯誤檢查,而不是僅在該進程的迭代之間進行。 –
這可能有所幫助:http://stackoverflow.com/questions/772355/how-to-inherit-from-stdostream – Skurmedel