首页 > 代码库 > istream, outstream使用及常见错误
istream, outstream使用及常见错误
使用方法:
使用filebuf打开文件,并拷贝给istream/ostream。
如下面的例子中,实现读取并处理deseq文件夹下所有文件,输出到ostream fw.
code:
头文件:
#include<iostream> #include<stdlib.h> #include<string.h> #include<stdio.h> #include<fstream> #include<dirent.h>
调用:
void process(char* filename){ std::filebuf fbOut,fbIn; fbOut.open("kw_fea.txt",std::ios::out); std::ostream fw(&fbOut); 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(fw); fbIn.close(); } } } }
其中,parsefile的声明为:bool parsefile(ostream &fw)
注意这里函数声明必须要加引用,不然会报错:
错误:
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 read.cpp:10:
/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_ostream<char, std::char_traits<char> >::basic_ostream(const std::basic_ostream<char, std::char_traits<char> >&)‘:
/usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/iosfwd:56: 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
read.cpp: In function ‘void process(char*)‘:
read.cpp:105: note: synthesized method ‘std::basic_ostream<char, std::char_traits<char> >::basic_ostream(const std::basic_ostream<char, std::char_traits<char> >&)‘ first required here
read.cpp:105: error: initializing argument 1 of ‘bool parsefile(std::ostream)‘
原因是stream类型数据不支持拷贝,所以必须传址。
参考:http://stackoverflow.com/questions/6457591/problem-with-ostream-ofstream-inheritance
istream, outstream使用及常见错误