istream, outstream使用及常见错误
2016-04-05 12:45 GarfieldEr007 阅读(830) 评论(0) 编辑 收藏 举报使用方法:
使用filebuf打开文件,并拷贝给istream/ostream。
如下面的例子中,实现读取并处理deseq文件夹下所有文件,输出到ostream fw.
code:
- #include<iostream>
- #include<stdlib.h>
- #include<string>
- #include<stdio.h>
- #include<fstream>
- #include<dirent.h>
- using namespace std;
- void parsefile(istream& fi, ostream& fo){
- string tmp;
- while(fi>>tmp){
- fo<<tmp<<endl;
- }
- }
- void process(){
- std::filebuf fbOut,fbIn;
- fbOut.open("out.txt",std::ios::out);
- std::ostream fw(&fbOut);
- // Basic function testing
- fbIn.open("test.cpp",ios::in);
- istream is(&fbIn);
- parsefile(is,fw);
- // get all files in this directory and print it to "out.txt" iteratively
- DIR* dir;
- struct dirent* ent;
- if((dir = opendir("deseq"))!=NULL){
- while((ent = readdir(dir))!=NULL){
- char* filename = ent->d_name;
- if (fbIn.open(filename,ios::in)){
- istream is(&fbIn);
- parsefile(is,fw);//read from is and write in fw
- fbIn.close();
- }
- }
- }
- }
- int main(){
- process();
- return 0;
- }
其中,parsefile的声明为:void parsefile(istream& fi, ostream& fo)
注意这里函数声明必须要加引用,不然会报错:
错误:
$ g++ -g test.cpp -o b.out
In file included from /usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/ios:39,
from /usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/ostream:40,
from /usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/iostream:40,
from test.cpp:1:
/usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/bits/ios_base.h: In copy constructor 'std::basic_ios<char, std::char_traits<char> >::basic_ios(const std::basic_ios<char, std::char_traits<char> >&)':
/usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/bits/ios_base.h:790: error: 'std::ios_base::ios_base(const std::ios_base&)' is private
/usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/iosfwd:47: error: within this context
/usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/iosfwd: In copy constructor 'std::basic_istream<char, std::char_traits<char> >::basic_istream(const std::basic_istream<char, std::char_traits<char> >&)':
/usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/iosfwd:53: note: synthesized method 'std::basic_ios<char, std::char_traits<char> >::basic_ios(const std::basic_ios<char, std::char_traits<char> >&)' first required here
test.cpp: In function 'void process()':
test.cpp:24: note: synthesized method 'std::basic_istream<char, std::char_traits<char> >::basic_istream(const std::basic_istream<char, std::char_traits<char> >&)' first required here
test.cpp:24: error: initializing argument 1 of 'void parsefile(std::istream, std::ostream)'
原因是stream类型数据不支持拷贝,所以必须传址。
参考:http://stackoverflow.com/questions/6457591/problem-with-ostream-ofstream-inheritance
from: http://blog.csdn.net/abcjennifer/article/details/41545655