流(Stream)是C++和C之间的一大区别。写C++的程序员都知道流的用法。在Poco库中,在标准流的基础上又扩充了一些流,分别是基于Base64和HexBinary的编解码流,使用zlib的数据压缩流,二进制的I/O流,文件流,以及一些其他的辅助流;另外Poco库还提供了一个扩展的结构,用于创建用户自定义流。
Poco库中所有的流类都与标准c++库中的流兼容。并且在Poco库中,大多数流都仅仅是个过滤器,这意味着它们不会直接从设备中读取或者写入数据,通常情况下它们会链接到另一个流上。下面我们分别对它们进行介绍。
1. 读取/设置流的格式
fmtflags flags() const; fmtflags flags (fmtflags fmtfl);例子:
// modify flags #include <iostream> // std::cout, std::ios int main () { std::cout.flags ( std::ios::right | std::ios::hex | std::ios::showbase ); std::cout.width (10); std::cout << 100 << '\n'; return 0; }
fmtflags setf (fmtflags fmtfl); fmtflags setf (fmtflags fmtfl, fmtflags mask);例子:
// modifying flags with setf/unsetf #include <iostream> // std::cout, std::ios int main () { std::cout.setf ( std::ios::hex, std::ios::basefield ); // set hex as the basefield std::cout.setf ( std::ios::showbase ); // activate showbase std::cout << 100 << '\n'; std::cout.unsetf ( std::ios::showbase ); // deactivate showbase std::cout << 100 << '\n'; return 0; }输出:
void unsetf (fmtflags mask);例子:
// modifying flags with setf/unsetf #include <iostream> // std::cout, std::ios int main () { std::cout.setf ( std::ios::hex, std::ios::basefield ); // set hex as the basefield std::cout.setf ( std::ios::showbase ); // activate showbase std::cout << 100 << '\n'; std::cout.unsetf ( std::ios::showbase ); // deactivate showbase std::cout << 100 << '\n'; return 0; }输出:
streamsize precision() const; streamsize precision (streamsize prec);例子:
// modify precision #include <iostream> // std::cout, std::ios int main () { double f = 3.14159; std::cout.unsetf ( std::ios::floatfield ); // floatfield not set std::cout.precision(5); std::cout << f << '\n'; std::cout.precision(10); std::cout << f << '\n'; std::cout.setf( std::ios::fixed, std:: ios::floatfield ); // floatfield set to fixed std::cout << f << '\n'; return 0; }输出:
streamsize width() const; streamsize width (streamsize wide);例子:
// field width #include <iostream> // std::cout, std::left int main () { std::cout << 100 << '\n'; std::cout.width(10); std::cout << 100 << '\n'; std::cout.fill('x'); std::cout.width(15); std::cout << std::left << 100 << '\n'; return 0; }输出:
locale imbue (const locale& loc);例子:
// imbue example #include <iostream> // std::cout #include <locale> // std::locale int main() { std::locale mylocale(""); // get global locale std::cout.imbue(mylocale); // imbue global locale std::cout << 3.14159 << '\n'; return 0; }
输出:
3,14159
locale getloc() const;
template <class Elem, class Traits> class basic_ios : public ios_base { //C++标准库封装了一个缓冲区类streambuf,以供输入输出流对象使用。 //每个标准C++输出输出流对象都包含一个指向streambuf的指针, basic_streambuf<_Elem, _Traits>*_Mystrbuf; // .... }
bool good() const; //检查流状态位是否为good bool eof() const; //检查流状态位是否为eof,eofbit位被标志 bool fail() const; //检查流状态位是否为fail,failbit或者badbit被标志 bool bad() const; //检查流状态位是否为bad,badbit位被标志 iostate rdstate() const; //返回流状态位
iostate value (member constant) |
indicates | functions to check state flags | ||||
---|---|---|---|---|---|---|
good() | eof() | fail() | bad() | rdstate() | ||
goodbit | No errors (zero value iostate) | true |
false |
false |
false |
goodbit |
eofbit | End-of-File reached on input operation | false |
true |
false |
false |
eofbit |
failbit | Logical error on i/o operation | false |
false |
true |
false |
failbit |
badbit | Read/writing error on i/o operation | false |
false |
true |
true |
badbit |
// error state flags #include <iostream> // std::cout, std::ios #include <sstream> // std::stringstream void print_state (const std::ios& stream) { std::cout << " good()=" << stream.good(); std::cout << " eof()=" << stream.eof(); std::cout << " fail()=" << stream.fail(); std::cout << " bad()=" << stream.bad(); } int main () { std::stringstream stream; stream.clear (stream.goodbit); std::cout << "goodbit:"; print_state(stream); std::cout << '\n'; stream.clear (stream.eofbit); std::cout << " eofbit:"; print_state(stream); std::cout << '\n'; stream.clear (stream.failbit); std::cout << "failbit:"; print_state(stream); std::cout << '\n'; stream.clear (stream.badbit); std::cout << " badbit:"; print_state(stream); std::cout << '\n'; return 0; }输出:
bool operator!() const;如果没有错误标记被设置(failbit或badbit),返回true,否则返回false
void setstate (iostate state); void clear (iostate state = goodbit);有两种方法可以设置输入/输出的状态信息。clear()函数可以使流状态将按照ios_base::iostate所描述的样子进行设置。ios::failbit、ios::badbit、ios::eofbit、ios::goodbit均为常量,它们中的任何一个都代表了一种流状态,或可被称为“输入状态标记位常量”。它们不是failbit、badbit、eofbit、goodbit这四个标记位的存贮变量。标记为常量的状态如上表所述。
例子:
// clearing errors #include <iostream> // std::cout #include <fstream> // std::fstream int main () { char buffer [80]; std::fstream myfile; myfile.open ("test.txt",std::fstream::in); myfile << "test"; if (myfile.fail()) { std::cout << "Error writing to test.txt\n"; myfile.clear(); } myfile.getline (buffer,80); std::cout << buffer << " successfully read from file.\n"; return 0; }
void basic_ios::setstate (iostate state) { clear(rdstate()|state); }
basic_ios& copyfmt (const basic_ios& rhs);
// copying formatting information #include <iostream> // std::cout #include <fstream> // std::ofstream int main () { std::ofstream filestr; filestr.open ("test.txt"); std::cout.fill ('*'); std::cout.width (10); filestr.copyfmt (std::cout); std::cout << 40; filestr << 40; return 0; }
char_type fill() const; char_type fill (char_type fillch);
// using the fill character #include <iostream> // std::cout int main () { char prev; std::cout.width (10); std::cout << 40 << '\n'; prev = std::cout.fill ('x'); std::cout.width (10); std::cout << 40 << '\n'; std::cout.fill(prev); return 0; }输出:
iostate exceptions() const; void exceptions (iostate except);
// basic_ios::exceptions #include <iostream> // std::cerr #include <fstream> // std::ifstream int main () { std::ifstream file; file.exceptions ( std::ifstream::failbit | std::ifstream::badbit ); try { file.open ("test.txt"); while (!file.eof()) file.get(); } catch (std::ifstream::failure e) { std::cerr << "Exception opening/reading file"; } file.close(); return 0; }
basic_ostream<char_type,traits_type>* tie() const; basic_ostream<char_type,traits_type>* tie (basic_ostream<char_type,traits_type>* tiestr);
// redefine tied object #include <iostream> // std::ostream, std::cout, std::cin #include <fstream> // std::ofstream int main () { std::ostream *prevstr; std::ofstream ofs; ofs.open ("test.txt"); std::cout << "tie example:\n"; *std::cin.tie() << "This is inserted into cout"; prevstr = std::cin.tie (&ofs); *std::cin.tie() << "This is inserted into the file"; std::cin.tie (prevstr); ofs.close(); return 0; }输出:
basic_streambuf<char_type,traits_type>* rdbuf() const; basic_streambuf<char_type,traits_type>* rdbuf (basic_streambuf<char_type,traits_type>* sb);
// redirecting cout's output thrrough its stream buffer #include <iostream> // std::streambuf, std::cout #include <fstream> // std::ofstream int main () { std::streambuf *psbuf, *backup; std::ofstream filestr; filestr.open ("test.txt"); backup = std::cout.rdbuf(); // back up cout's streambuf psbuf = filestr.rdbuf(); // get file's streambuf std::cout.rdbuf(psbuf); // assign streambuf to cout std::cout << "This is written to the file"; std::cout.rdbuf(backup); // restore cout's original streambuf filestr.close(); return 0; }
char narrow (char_type wc, char dfault) const;返回c对应的宽字符
char_type widen (char c) const;
explicit istream (streambuf* sb);
// istream constructor #include <iostream> // std::ios, std::istream, std::cout #include <fstream> // std::filebuf int main () { std::filebuf fb; if (fb.open ("test.txt",std::ios::in)) { std::istream is(&fb); while (is) std::cout << char(is.get()); fb.close(); } return 0; }
istream& operator>> (bool& val); istream& operator>> (short& val); istream& operator>> (unsigned short& val); istream& operator>> (int& val); istream& operator>> (unsigned int& val); istream& operator>> (long& val); istream& operator>> (unsigned long& val); istream& operator>> (float& val); istream& operator>> (double& val); istream& operator>> (long double& val); istream& operator>> (void*& val); stream buffers (2) istream& operator>> (streambuf* sb ); manipulators (3) istream& operator>> (istream& (*pf)(istream&)); istream& operator>> (ios& (*pf)(ios&)); istream& operator>> (ios_base& (*pf)(ios_base&));
// example on extraction #include <iostream> // std::cin, std::cout, std::hex int main () { int n; std::cout << "Enter a number: "; std::cin >> n; std::cout << "You have entered: " << n << '\n'; std::cout << "Enter a hexadecimal number: "; std::cin >> std::hex >> n; // manipulator std::cout << "Its decimal equivalent is: " << n << '\n'; return 0; }
streamsize gcount() const;获取最后一次执行析取操作所读取的字符串数目
例子:
// cin.gcount example #include <iostream> // std::cin, std::cout int main () { char str[20]; std::cout << "Please, enter a word: "; std::cin.getline(str,20); std::cout << std::cin.gcount() << " characters read: " << str << '\n'; return 0; }输出:
int get() istream& get (char& c) istream& get (char* s, streamsize n) istream& get (char* s, streamsize n, char delim) istream& get (streambuf& sb) istream& get (streambuf& sb, char delim)
// istream::get example #include <iostream> // std::cin, std::cout #include <fstream> // std::ifstream int main () { char str[256]; std::cout << "Enter the name of an existing text file: "; std::cin.get (str,256); // get c-string std::ifstream is(str); // open file while (is.good()) // loop while extraction from file is possible { char c = is.get(); // get character from file if (is.good()) std::cout << c; } is.close(); // close file return 0; }
istream& getline (char* s, streamsize n ); istream& getline (char* s, streamsize n, char delim );
// istream::getline example #include <iostream> // std::cin, std::cout int main () { char name[256], title[256]; std::cout << "Please, enter your name: "; std::cin.getline (name,256); std::cout << "Please, enter your favourite movie: "; std::cin.getline (title,256); std::cout << name << "'s favourite movie is " << title; return 0; }
istream& ignore (streamsize n = 1, int delim = EOF);
// istream::ignore example #include <iostream> // std::cin, std::cout int main () { char first, last; std::cout << "Please, enter your first name followed by your surname: "; first = std::cin.get(); // get one character std::cin.ignore(256,' '); // ignore until space last = std::cin.get(); // get one character std::cout << "Your initials are " << first << last << '\n'; return 0; }
int peek();
// istream::peek example #include <iostream> // std::cin, std::cout #include <string> // std::string int main () { std::cout << "Please, enter a number or a word: "; char c = std::cin.peek(); if ( (c >= '0') && (c <= '9') ) { int n; std::cin >> n; std::cout << "You entered the number: " << n << '\n'; } else { std::string str; std::getline (std::cin, str); std::cout << "You entered the word: " << str << '\n'; } return 0; }输出:
istream& read (char* s, streamsize n);
// read a file into memory #include <iostream> // std::cout #include <fstream> // std::ifstream int main () { std::ifstream is ("test.txt", std::ifstream::binary); if (is) { // get length of file: is.seekg (0, is.end); int length = is.tellg(); is.seekg (0, is.beg); char * buffer = new char [length]; std::cout << "Reading " << length << " characters... "; // read data as a block: is.read (buffer,length); if (is) std::cout << "all characters read successfully."; else std::cout << "error: only " << is.gcount() << " could be read"; is.close(); // ...buffer contains the entire file... delete[] buffer; } return 0; }输出:
streamsize readsome (char* s, streamsize n);
istream& putback (char c);
// istream::putback example #include <iostream> // std::cin, std::cout #include <string> // std::string int main () { std::cout << "Please, enter a number or a word: "; char c = std::cin.get(); if ( (c >= '0') && (c <= '9') ) { int n; std::cin.putback (c); std::cin >> n; std::cout << "You entered a number: " << n << '\n'; } else { std::string str; std::cin.putback (c); getline (std::cin,str); std::cout << "You entered a word: " << str << '\n'; } return 0; }输出:
istream& unget();
// istream::unget example #include <iostream> // std::cin, std::cout #include <string> // std::string int main () { std::cout << "Please, enter a number or a word: "; char c = std::cin.get(); if ( (c >= '0') && (c <= '9') ) { int n; std::cin.unget(); std::cin >> n; std::cout << "You entered a number: " << n << '\n'; } else { std::string str; std::cin.unget(); getline (std::cin,str); std::cout << "You entered a word: " << str << '\n'; } return 0; }输出:
streampos tellg();
// read a file into memory #include <iostream> // std::cout #include <fstream> // std::ifstream int main () { std::ifstream is ("test.txt", std::ifstream::binary); if (is) { // get length of file: is.seekg (0, is.end); int length = is.tellg(); is.seekg (0, is.beg); // allocate memory: char * buffer = new char [length]; // read data as a block: is.read (buffer,length); is.close(); // print content: std::cout.write (buffer,length); delete[] buffer; } return 0; }
istream& seekg (streampos pos); istream& seekg (streamoff off, ios_base::seekdir way);
int sync();
// syncing input stream #include <iostream> // std::cin, std::cout int main () { char first, second; std::cout << "Please, enter a word: "; first = std::cin.get(); std::cin.sync(); std::cout << "Please, enter another word: "; second = std::cin.get(); std::cout << "The first word began by " << first << '\n'; std::cout << "The second word began by " << second << '\n'; return 0; }输出:
explicit ostream (streambuf* sb);
// ostream constructor #include <iostream> // std::cout, std::ostream, std::ios #include <fstream> // std::filebuf int main () { std::filebuf fb; fb.open ("test.txt",std::ios::out); std::ostream os(&fb); os << "Test sentence\n"; fb.close(); return 0; }
ostream& operator<< (bool val); ostream& operator<< (short val); ostream& operator<< (unsigned short val); ostream& operator<< (int val); ostream& operator<< (unsigned int val); ostream& operator<< (long val); ostream& operator<< (unsigned long val); ostream& operator<< (float val); ostream& operator<< (double val); ostream& operator<< (long double val); ostream& operator<< (void* val); ostream& operator<< (streambuf* sb ); ostream& operator<< (ostream& (*pf)(ostream&)); ostream& operator<< (ios& (*pf)(ios&)); ostream& operator<< (ios_base& (*pf)(ios_base&));
// example on insertion #include <iostream> // std::cout, std::right, std::endl #include <iomanip> // std::setw int main () { int val = 65; std::cout << std::right; // right-adjusted (manipulator) std::cout << std::setw(10); // set width (extended manipulator) std::cout << val << std::endl; // multiple insertions return 0; }输出:
ostream& put (char c);
// typewriter #include <iostream> // std::cin, std::cout #include <fstream> // std::ofstream int main () { std::ofstream outfile ("test.txt"); char ch; std::cout << "Type some text (type a dot to finish):\n"; do { ch = std::cin.get(); outfile.put(ch); } while (ch!='.'); return 0; }
ostream& write (const char* s, streamsize n);
// Copy a file #include <fstream> // std::ifstream, std::ofstream int main () { std::ifstream infile ("test.txt",std::ifstream::binary); std::ofstream outfile ("new.txt",std::ofstream::binary); // get size of file infile.seekg (0,infile.end); long size = infile.tellg(); infile.seekg (0); // allocate memory for file content char* buffer = new char[size]; // read content of infile infile.read (buffer,size); // write to outfile outfile.write (buffer,size); // release dynamically-allocated memory delete[] buffer; outfile.close(); infile.close(); return 0; }
streampos tellp();
// position in output stream #include <fstream> // std::ofstream int main () { std::ofstream outfile; outfile.open ("test.txt"); outfile.write ("This is an apple",16); long pos = outfile.tellp(); outfile.seekp (pos-7); outfile.write (" sam",4); outfile.close(); return 0; }输出:
ostream& seekp (streampos pos); ostream& seekp (streamoff off, ios_base::seekdir way);
member constant | seeking relative to |
---|---|
beg | beginning of sequence. |
cur | current position within sequence. |
end | end of sequence. |
// position in output stream #include <fstream> // std::ofstream int main () { std::ofstream outfile; outfile.open ("test.txt"); outfile.write ("This is an apple",16); long pos = outfile.tellp(); outfile.seekp (pos-7); outfile.write (" sam",4); outfile.close(); return 0; }
ostream& flush();
// Flushing files #include <fstream> // std::ofstream int main () { std::ofstream outfile ("test.txt"); for (int n=0; n<100; ++n) { outfile << n; outfile.flush(); } outfile.close(); return 0; }
ofstream(); explicit ofstream (const char* filename, ios_base::openmode mode = ios_base::out);
// ofstream constructor. #include <fstream> // std::ofstream int main () { std::ofstream ofs ("test.txt", std::ofstream::out); ofs << "lorem ipsum"; ofs.close(); return 0; }
void open (const char* filename, ios_base::openmode mode = ios_base::out);
member constant | stands for | access |
---|---|---|
in | input | File open for reading: the internal stream buffer supports input operations. |
out | output | File open for writing: the internal stream buffer supports output operations. |
binary | binary | Operations are performed in binary mode rather than text. |
ate | at end | The output position starts at the end of the file. |
app | append | All output operations happen at the end of the file, appending to its existing contents. |
trunc | truncate | Any contents that existed in the file before it is open are discarded. |
fstream(filename, ios::in|ios::out|ios::ate)。
// ofstream::open / ofstream::close #include <fstream> // std::ofstream int main () { std::ofstream ofs; ofs.open ("test.txt", std::ofstream::out | std::ofstream::app); ofs << " more lorem ipsum"; ofs.close(); return 0; }
bool is_open();在函数内部调用rdbuf()->is_open();
// ofstream::is_open #include <iostream> // std::cout #include <fstream> // std::ofstream int main () { std::ofstream ofs; ofs.open ("test.txt"); if (ofs.is_open()) { ofs << "lorem ipsum"; std::cout << "Output operation successfully performed\n"; ofs.close(); } else { std::cout << "Error opening file"; } return 0; }输出:
void close();
// ofstream::open / ofstream::close #include <fstream> // std::ofstream int main () { std::ofstream ofs; ofs.open ("test.txt", std::ofstream::out | std::ofstream::app); ofs << " more lorem ipsum"; ofs.close(); return 0; }
filebuf* rdbuf() const;
// copy a file using file stream buffers #include <fstream> // std::filebuf, std::ifstream, std::ofstream #include <cstdio> // EOF int main () { std::ifstream ifs ("test.txt"); std::ofstream ofs ("copy.txt"); std::filebuf* inbuf = ifs.rdbuf(); std::filebuf* outbuf = ofs.rdbuf(); char c = inbuf->sbumpc(); while (c != EOF) { outbuf->sputc (c); c = inbuf->sbumpc(); } ofs.close(); ifs.close(); return 0; }
ifstream(); explicit ifstream (const char* filename, ios_base::openmode mode = ios_base::in);
// ifstream constructor. #include <iostream> // std::cout #include <fstream> // std::ifstream int main () { std::ifstream ifs ("test.txt", std::ifstream::in); char c = ifs.get(); while (ifs.good()) { std::cout << c; c = ifs.get(); } ifs.close(); return 0; }
void open (const char* filename, ios_base::openmode mode = ios_base::in);
// print the content of a text file. #include <iostream> // std::cout #include <fstream> // std::ifstream int main () { std::ifstream ifs; ifs.open ("test.txt", std::ifstream::in); char c = ifs.get(); while (ifs.good()) { std::cout << c; c = ifs.get(); } ifs.close(); return 0; }
bool is_open();
// ifstream::is_open #include <iostream> // std::cout #include <fstream> // std::ifstream int main () { std::ifstream ifs ("test.txt"); if (ifs.is_open()) { // print file: char c = ifs.get(); while (ifs.good()) { std::cout << c; c = ifs.get(); } } else { // show message: std::cout << "Error opening file"; } return 0; }
void close();
// print the content of a text file. #include <iostream> // std::cout #include <fstream> // std::ifstream int main () { std::ifstream ifs; ifs.open ("test.txt"); char c = ifs.get(); while (ifs.good()) { std::cout << c; c = ifs.get(); } ifs.close(); return 0; }
filebuf* rdbuf() const;
// read file data using associated buffer's members #include <iostream> // std::cout #include <fstream> // std::filebuf, std::ifstream int main () { std::ifstream ifs ("test.txt", std::ifstream::binary); // get pointer to associated buffer object std::filebuf* pbuf = ifs.rdbuf(); // get file size using buffer's members std::size_t size = pbuf->pubseekoff (0,ifs.end,ifs.in); pbuf->pubseekpos (0,ifs.in); // allocate memory to contain file data char* buffer=new char[size]; // get file data pbuf->sgetn (buffer,size); ifs.close(); // write content to stdout std::cout.write (buffer,size); delete[] buffer; return 0; }
explicit ostringstream (ios_base::openmode which = ios_base::out); explicit ostringstream (const string& str, ios_base::openmode which = ios_base::out);
// ostringstream constructor #include <iostream> // std::cout, std::ios #include <sstream> // std::ostringstream int main () { std::ostringstream foo; // out std::ostringstream bar (std::ostringstream::ate); // out|ate foo.str("Test string"); bar.str("Test string"); foo << 101; bar << 101; std::cout << foo.str() << '\n'; std::cout << bar.str() << '\n'; return 0; }输出:
string str() const; void str (const string& s);
// ostringstream::rdbuf #include <string> // std::string #include <iostream> // std::cout #include <sstream> // std::ostringstream int main () { std::ostringstream oss; oss << "One hundred and one: " << 101; std::string s = oss.str(); std::cout << s << '\n'; return 0; }
输出:
One hundred and one: 101ostream& operator<< (bool val); ostream& operator<< (short val); ostream& operator<< (unsigned short val); ostream& operator<< (int val); ostream& operator<< (unsigned int val); ostream& operator<< (long val); ostream& operator<< (unsigned long val); ostream& operator<< (float val); ostream& operator<< (double val); ostream& operator<< (long double val); ostream& operator<< (void* val); ostream& operator<< (streambuf* sb ); ostream& operator<< (ostream& (*pf)(ostream&)); ostream& operator<< (ios& (*pf)(ios&)); ostream& operator<< (ios_base& (*pf)(ios_base&));
// example on insertion #include <iostream> // std::cout, std::right, std::endl #include <iomanip> // std::setw int main () { int val = 65; std::cout << std::right; // right-adjusted (manipulator) std::cout << std::setw(10); // set width (extended manipulator) std::cout << val << std::endl; // multiple insertions return 0; }输出:
ostream& put (char c);
// typewriter #include <iostream> // std::cin, std::cout #include <fstream> // std::ofstream int main () { std::ofstream outfile ("test.txt"); char ch; std::cout << "Type some text (type a dot to finish):\n"; do { ch = std::cin.get(); outfile.put(ch); } while (ch!='.'); return 0; }
ostream& write (const char* s, streamsize n);
// Copy a file #include <fstream> // std::ifstream, std::ofstream int main () { std::ifstream infile ("test.txt",std::ifstream::binary); std::ofstream outfile ("new.txt",std::ofstream::binary); // get size of file infile.seekg (0,infile.end); long size = infile.tellg(); infile.seekg (0); // allocate memory for file content char* buffer = new char[size]; // read content of infile infile.read (buffer,size); // write to outfile outfile.write (buffer,size); // release dynamically-allocated memory delete[] buffer; outfile.close(); infile.close(); return 0; }
streampos tellp();
// position in output stream #include <fstream> // std::ofstream int main () { std::ofstream outfile; outfile.open ("test.txt"); outfile.write ("This is an apple",16); long pos = outfile.tellp(); outfile.seekp (pos-7); outfile.write (" sam",4); outfile.close(); return 0; }
ostream& seekp (streampos pos); ostream& seekp (streamoff off, ios_base::seekdir way);
// position in output stream #include <fstream> // std::ofstream int main () { std::ofstream outfile; outfile.open ("test.txt"); outfile.write ("This is an apple",16); long pos = outfile.tellp(); outfile.seekp (pos-7); outfile.write (" sam",4); outfile.close(); return 0; }输出:
ostream& flush();
// Flushing files #include <fstream> // std::ofstream int main () { std::ofstream outfile ("test.txt"); for (int n=0; n<100; ++n) { outfile << n; outfile.flush(); } outfile.close(); return 0; }
explicit istringstream (ios_base::openmode which = ios_base::in); explicit istringstream (const string& str, ios_base::openmode which = ios_base::in);
// istringstream constructors. #include <iostream> // std::cout #include <sstream> // std::istringstream #include <string> // std::string int main () { std::string stringvalues = "125 320 512 750 333"; std::istringstream iss (stringvalues); for (int n=0; n<5; n++) { int val; iss >> val; std::cout << val*2 << '\n'; } return 0; }输出:
string str() const; void str (const string& s);
// istringstream::str #include <string> // std::string #include <iostream> // std::cout #include <sstream> // std::istringstream int main () { std::istringstream iss; std::string strvalues = "32 240 2 1450"; iss.str (strvalues); for (int n=0; n<4; n++) { int val; iss >> val; std::cout << val << '\n'; } std::cout << "Finished writing the numbers in: "; std::cout << iss.str() << '\n'; return 0; }输出:
stringbuf* rdbuf() const;
// istringstream::rdbuf #include <string> // std::string #include <iostream> // std::cout #include <sstream> // std::istringstream, std::stringbuf int main () { std::istringstream iss; std::stringbuf *pbuf = iss.rdbuf(); // using stringbuf directly: pbuf->str("Example string"); int size = pbuf->in_avail(); while (pbuf->in_avail()>0) std::cout << static_cast<char>(pbuf->sbumpc()); return 0; }输出:
istream& operator>> (bool& val); istream& operator>> (short& val); istream& operator>> (unsigned short& val); istream& operator>> (int& val); istream& operator>> (unsigned int& val); istream& operator>> (long& val); istream& operator>> (unsigned long& val); istream& operator>> (float& val); istream& operator>> (double& val); istream& operator>> (long double& val); istream& operator>> (void*& val); istream& operator>> (streambuf* sb ); istream& operator>> (istream& (*pf)(istream&)); istream& operator>> (ios& (*pf)(ios&)); istream& operator>> (ios_base& (*pf)(ios_base&));
// example on extraction #include <iostream> // std::cin, std::cout, std::hex int main () { int n; std::cout << "Enter a number: "; std::cin >> n; std::cout << "You have entered: " << n << '\n'; std::cout << "Enter a hexadecimal number: "; std::cin >> std::hex >> n; // manipulator std::cout << "Its decimal equivalent is: " << n << '\n'; return 0; }
streamsize gcount() const;
// cin.gcount example #include <iostream> // std::cin, std::cout int main () { char str[20]; std::cout << "Please, enter a word: "; std::cin.getline(str,20); std::cout << std::cin.gcount() << " characters read: " << str << '\n'; return 0; }输出:
int get(); istream& get (char& c); istream& get (char* s, streamsize n); istream& get (char* s, streamsize n, char delim); istream& get (streambuf& sb); istream& get (streambuf& sb, char delim);
// istream::get example #include <iostream> // std::cin, std::cout #include <fstream> // std::ifstream int main () { char str[256]; std::cout << "Enter the name of an existing text file: "; std::cin.get (str,256); // get c-string std::ifstream is(str); // open file while (is.good()) // loop while extraction from file is possible { char c = is.get(); // get character from file if (is.good()) std::cout << c; } is.close(); // close file return 0; }
istream& getline (char* s, streamsize n ); istream& getline (char* s, streamsize n, char delim );
// istream::getline example #include <iostream> // std::cin, std::cout int main () { char name[256], title[256]; std::cout << "Please, enter your name: "; std::cin.getline (name,256); std::cout << "Please, enter your favourite movie: "; std::cin.getline (title,256); std::cout << name << "'s favourite movie is " << title; return 0; }
istream& ignore (streamsize n = 1, int delim = EOF);
// istream::ignore example #include <iostream> // std::cin, std::cout int main () { char first, last; std::cout << "Please, enter your first name followed by your surname: "; first = std::cin.get(); // get one character std::cin.ignore(256,' '); // ignore until space last = std::cin.get(); // get one character std::cout << "Your initials are " << first << last << '\n'; return 0; }输出:
int peek();
例子:
// istream::peek example #include <iostream> // std::cin, std::cout #include <string> // std::string int main () { std::cout << "Please, enter a number or a word: "; char c = std::cin.peek(); if ( (c >= '0') && (c <= '9') ) { int n; std::cin >> n; std::cout << "You entered the number: " << n << '\n'; } else { std::string str; std::getline (std::cin, str); std::cout << "You entered the word: " << str << '\n'; } return 0; }输出:
istream& read (char* s, streamsize n);
// read a file into memory #include <iostream> // std::cout #include <fstream> // std::ifstream int main () { std::ifstream is ("test.txt", std::ifstream::binary); if (is) { // get length of file: is.seekg (0, is.end); int length = is.tellg(); is.seekg (0, is.beg); char * buffer = new char [length]; std::cout << "Reading " << length << " characters... "; // read data as a block: is.read (buffer,length); if (is) std::cout << "all characters read successfully."; else std::cout << "error: only " << is.gcount() << " could be read"; is.close(); // ...buffer contains the entire file... delete[] buffer; } return 0; }输出:
streamsize readsome (char* s, streamsize n);
istream& putback (char c);
// istream::putback example #include <iostream> // std::cin, std::cout #include <string> // std::string int main () { std::cout << "Please, enter a number or a word: "; char c = std::cin.get(); if ( (c >= '0') && (c <= '9') ) { int n; std::cin.putback (c); std::cin >> n; std::cout << "You entered a number: " << n << '\n'; } else { std::string str; std::cin.putback (c); getline (std::cin,str); std::cout << "You entered a word: " << str << '\n'; } return 0; }输出:
istream& unget();
// istream::unget example #include <iostream> // std::cin, std::cout #include <string> // std::string int main () { std::cout << "Please, enter a number or a word: "; char c = std::cin.get(); if ( (c >= '0') && (c <= '9') ) { int n; std::cin.unget(); std::cin >> n; std::cout << "You entered a number: " << n << '\n'; } else { std::string str; std::cin.unget(); getline (std::cin,str); std::cout << "You entered a word: " << str << '\n'; } return 0; }输出:
streampos tellg();
// read a file into memory #include <iostream> // std::cout #include <fstream> // std::ifstream int main () { std::ifstream is ("test.txt", std::ifstream::binary); if (is) { // get length of file: is.seekg (0, is.end); int length = is.tellg(); is.seekg (0, is.beg); // allocate memory: char * buffer = new char [length]; // read data as a block: is.read (buffer,length); is.close(); // print content: std::cout.write (buffer,length); delete[] buffer; } return 0; }
istream& seekg (streampos pos); istream& seekg (streamoff off, ios_base::seekdir way);
// read a file into memory #include <iostream> // std::cout #include <fstream> // std::ifstream int main () { std::ifstream is ("test.txt", std::ifstream::binary); if (is) { // get length of file: is.seekg (0, is.end); int length = is.tellg(); is.seekg (0, is.beg); // allocate memory: char * buffer = new char [length]; // read data as a block: is.read (buffer,length); is.close(); // print content: std::cout.write (buffer,length); delete[] buffer; } return 0; }
int sync();
// syncing input stream #include <iostream> // std::cin, std::cout int main () { char first, second; std::cout << "Please, enter a word: "; first = std::cin.get(); std::cin.sync(); std::cout << "Please, enter another word: "; second = std::cin.get(); std::cout << "The first word began by " << first << '\n'; std::cout << "The second word began by " << second << '\n'; return 0; }输出:
locale pubimbue (const locale& loc);
locale getloc() const;
streambuf* pubsetbuf (char* s, streamsize n);
// set character buffer (pubsetbuf) #include <fstream> // std::fstream int main () { char mybuffer [512]; std::fstream filestr; filestr.rdbuf()->pubsetbuf(mybuffer,512); // operations with file stream here. return 0; }
streampos pubseekoff (streamoff off, ios_base::seekdir way, ios_base::openmode which = ios_base::in | ios_base::out);
// get file size using pubseekoff #include <iostream> // std::cout, std::streambuf #include <fstream> // std::fstream int main () { std::fstream filestr ("test.txt"); if (filestr) { std::streambuf* pbuf = filestr.rdbuf(); long size = pbuf->pubseekoff(0,filestr.end); std::cout << "The file size is " << size << " characters.\n"; filestr.close(); } return 0; }
streampos pubseekpos (streampos pos, ios_base::openmode which = ios_base::in | ios_base::out);
// changing position with pubseekpos #include <iostream> // std::cout, std::streambuf #include <fstream> // std::fstream int main () { std::fstream filestr ("test.txt"); if (filestr) { std::streambuf* pbuf = filestr.rdbuf(); long size = pbuf->pubseekoff(0,filestr.end); // get size if (size>20) { char buffer[11]; // change position to the 10th character pbuf->pubseekpos(10); // read 10 characters pbuf->sgetn (buffer,10); // append null character to string buffer[10]=0; std::cout << buffer << '\n'; } filestr.close(); } return 0; }
int pubsync();
// pubsync member #include <iostream> // std::cout, std::streambuf #include <fstream> // std::ofstream int main () { std::ofstream ostr ("test.txt"); if (ostr) { std::streambuf * pbuf = ostr.rdbuf(); pbuf->sputn ("First sentence\n",15); pbuf->pubsync(); pbuf->sputn ("Second sentence\n",16); ostr.close(); } return 0; }
streamsize in_avail();
// get file size using pubseekoff #include <iostream> // std::cout, std::streambuf, std::streamsize #include <fstream> // std::ifstream int main () { std::ifstream ifs ("test.txt"); if (ifs.good()) { std::streambuf* pbuf = ifs.rdbuf(); char c; ifs >> c; std::streamsize size = pbuf->in_avail(); std::cout << "first character in file: " << c << '\n'; std::cout << size << " characters in buffer after it\n"; } ifs.close(); return 0; }
int snextc();
// show file content - snextc() example #include <iostream> // std::cout, std::streambuf #include <fstream> // std::ifstream #include <cstdio> // EOF int main () { std::ifstream istr ("test.txt"); if (istr) { std::streambuf * pbuf = istr.rdbuf(); do { char ch = pbuf->sgetc(); std::cout << ch; } while ( pbuf->snextc() != EOF ); istr.close(); } return 0; }
int sbumpc();
// show file content - sbumpc() example #include <iostream> // std::cout, std::streambuf #include <fstream> // std::ifstream #include <cstdio> // EOF int main () { std::ifstream istr ("test.txt"); if (istr) { std::streambuf * pbuf = istr.rdbuf(); while ( pbuf->sgetc() != EOF ) { char ch = pbuf->sbumpc(); std::cout << ch; } istr.close(); } return 0; }
int sgetc();
// show file content - sgetc() example #include <iostream> // std::cout, std::streambuf #include <fstream> // std::ifstream #include <cstdio> // EOF int main () { std::ifstream istr ("test.txt"); if (istr) { std::streambuf * pbuf = istr.rdbuf(); do { char ch = pbuf->sgetc(); std::cout << ch; } while ( pbuf->snextc() != EOF ); istr.close(); } return 0; }
streamsize sgetn (char* s, streamsize n);
// read a file into buffer - sgetn() example #include <iostream> // std::cout, std::streambuf, std::streamsize #include <fstream> // std::ifstream int main () { char* contents; std::ifstream istr ("test.txt"); if (istr) { std::streambuf * pbuf = istr.rdbuf(); std::streamsize size = pbuf->pubseekoff(0,istr.end); pbuf->pubseekoff(0,istr.beg); // rewind contents = new char [size]; pbuf->sgetn (contents,size); istr.close(); std::cout.write (contents,size); } return 0; }
int sputbackc (char c);例子:
// sputbackc example #include <iostream> // std::cin, std::cout, std::streambuf, std::streamsize #include <cstdio> // EOF int main () { char ch; std::streambuf * pbuf = std::cin.rdbuf(); std::cout << "Please, enter some letters and then a number: "; do { ch = pbuf->sbumpc(); if ( (ch>='0') && (ch <='9') ) { pbuf->sputbackc (ch); long n; std::cin >> n; std::cout << "You entered number " << n << '\n'; break; } } while ( ch != EOF ); return 0; }
int sungetc();
// sputbackc example #include <iostream> // std::cin, std::cout, std::streambuf, std::streamsize #include <cstdio> // EOF int main () { char ch; std::streambuf * pbuf = std::cin.rdbuf(); std::cout << "Please, enter some letters and then a number: "; do { ch = pbuf->sbumpc(); if ( (ch>='0') && (ch <='9') ) { pbuf->sputbackc (ch); long n; std::cin >> n; std::cout << "You entered number " << n << '\n'; break; } } while ( ch != EOF ); return 0; }
int sputc (char c);
// typewriter - sputc() example #include <iostream> // std::cin, std::cout, std::streambuf #include <fstream> // std::ofstream int main () { char ch; std::ofstream ostr ("test.txt"); if (ostr) { std::cout << "Writing to file. Type a dot (.) to end.\n"; std::streambuf * pbuf = ostr.rdbuf(); do { ch = std::cin.get(); pbuf->sputc(ch); } while (ch!='.'); ostr.close(); } return 0; }
streamsize sputn (const char* s, streamsize n);
// sputn() example #include <iostream> // std::streambuf #include <fstream> // std::ofstream int main () { const char sentence[]= "Sample sentence"; std::ofstream ostr ("test.txt"); if (ostr) { std::streambuf * pbuf = ostr.rdbuf(); pbuf->sputn (sentence,sizeof(sentence)-1); ostr.close(); } return 0; }
filebuf* open (const char* filename, ios_base::openmode mode);
// filebuf::open() #include <iostream> #include <fstream> int main () { std::ifstream is; std::filebuf * fb = is.rdbuf(); fb->open ("test.txt",std::ios::out|std::ios::app); // >> appending operations here << fb->close(); return 0; }
bool is_open() const;
// filebuf::is_open() example #include <iostream> #include <fstream> int main () { std::ifstream is; std::filebuf * fb = is.rdbuf(); fb->open ("test.txt",std::ios::in); if ( fb->is_open() ) std::cout << "the file is open.\n"; else std::cout << "the file is not open.\n"; fb->close(); return 0; }
filebuf* close();
// filebuf::close() #include <iostream> #include <fstream> int main () { std::ifstream is; std::filebuf * fb = is.rdbuf(); fb->open ("test.txt",std::ios::in); // appending operations fb->close(); return 0; }
string str() const; void str (const string& str);
// stringbuf example #include <string> // std::string #include <iostream> // std::cout, std::ostream, std::hex #include <sstream> // std::stringbuf int main () { std::stringbuf buffer; // empty buffer std::ostream os (&buffer); // associate stream buffer to stream // mixing output to buffer with inserting to associated stream: buffer.sputn ("255 in hexadecimal: ",20); os << std::hex << 255; std::cout << buffer.str(); return 0; }
输出:
255 in hexadecimal: ff上面啰里啰唆的讲了半天,总结如下:
1. ios_base封装了流的格式
2. basic_ios封装了流的状态信息。并定义了指向streambuf的指针,也就是说:所有的流都关联一个缓冲区。在流构造时,必须显式的指定一个缓冲区streambuf的指针。文件流和字符串流在构造函数里,并没有看到streambuf指针参数,并不代表不需要,在其内部封装。所有流的输入输出操作都委托给了其内部的streambuf进行。
3. istream定义了输入操作,其中最重要的是重载了">>"操作符。
4. ostream定义了输出操作,其中最重要的是重载了"<<"操作符。
5. iostream多重继承于istream和ostream,能够同时完成读写功能。
6. ofstream、ifstream、fstream完成文件读写工作,定义了文件open,close接口。
7. ostringstream、istringstream、stringstream完成了对字符串的读写工作,定义了str接口。重载了"<<",">>"操作。
8. cerr(无缓冲标准错误)、clog(缓冲标准错误)、cout(缓冲标准输出)、cin(行缓冲)为标准库中预定义的stream对象。它们也关联有缓冲对象,其缓冲特性如下:
cerr(无缓冲标准错误) ----- 没有缓冲,发送给它的内容立即被输出
clog(缓冲标准错误) ----- 有缓冲,缓冲区满时输出
cout(缓冲标准输出) ----- 标准输出
附录:
在查阅C++流的相关资料时,发现有一篇文章很有意思,重点在底下的讨论。 文章链接为《C++的流设计很糟糕》。
(版权所有,转载时请注明作者和出处 http://blog.csdn.net/arau_sh/article/details/8698456)