文章目录
- 前言
- 一、IO类
- 二、文件输入输出
-
- 三、String流
前言
C++语言本身没有输入输出,而是通过定义在标准库中的类型来处理IO,这些类型支持从文件,控制台窗口读写数据,还有一些类型允许从内存IO中读写数据。
提示:以下是本篇文章正文内容,下面案例可供参考
一、IO类
1.IO库头文件和类型
1)、头文件iostream:从流读数据(istream,wistream),向流写数据(ostream,wostream),读写流(iostream,wiostream);
2)、头文件fstream:从文件 读数据(ifstream,wifstream),向文件写数据(ofstream,wofstream),读写文件(fstream,wfstream);
3)、头文件sstream:从string读数据(istringstream,wistringstream),向string写数据(ostringstream,wostringstream),读写 string(stringstream,wstringstream);
提示:带w字符开头的类型支持宽字符的输入输出。
2.IO对象不能被赋值,拷贝
fstream fs1,fs2;
fs1 = fs2;
void print(const ostream os);
void print(ostream& os);
void print(ostream* os);
3.流的条件状态
strm::iostate
strm::badbit
strm::failbit
strm::eofbit
strm::goodbit
fstream fs;
fs.eof();
fs.fail();
fs.bad();
fs.good();
fs.clear();
fs.clear(flags);
fs.setstate(flags);
fs.rdstate();
当流处于badbit状态时,流就无法使用了;如果流发生读字符错误时,属于流的操作失败了,在一定情况下可以被修复,则流可以继续使用;当达到文件结束位置,eofbit和failbit被置位;
3.管理输出缓冲
cout << "hello world" << endl;
cout << unitbuf;
cout << nounitbuf;
istream.tie();
istream.tie(&ostream);
cerr.tie(&cout);
cout.tie(&cin);
cin.tie(&cout);
二、文件输入输出
1.fstream的操作
代码如下:
fstream fs;
fstream fs(filepath);
fstream fs(filepath,mode);
fs.open(filename);
fs.close();
fs.is_open();
2.文件模式
代码如下:
fstream::in
fstream::out
fstream::trunc
fstream::app
fstream::ate
fstream::binary
ifstream ifs(filepath,fstream::in);
ofstream ofs(filepath,fstream::app);
ofstream ofs(filepath,fstream::out | fstream::trunc);
ofstream ofs(filepath,fstream::out);
fstream fs(filepath,fstream::in | fstream::out);
ofs.open(filepath);
三、String流
1.stringstream流的特有操作
sstream strm;
sstream strm(s);
strm.str();
strm.str(s);
2.sstringstream的读写操作
string s = "asdfadf";
sstringstream strings(s);
strings << "helloworld" ;
string s2;
strings >> s2;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)