c++读写流及读写文件

来源:互联网 发布:女装淘宝销量排行榜 编辑:程序博客网 时间:2024/06/07 16:30

IO 标准库类型和头文件

 

输出缓冲区的刷新
我们的程序已经使用过 endl 操纵符,用于输出一个换行符并刷新缓冲区。
除此之外,C++ 语言还提供了另外两个类似的操纵符。第一个经常使用的 flush,
用于刷新流,但不在输出中添加任何字符。第二个则是比较少用的 ends,这个
操纵符在缓冲区中插入空字符 null,然后后刷新它:
388
cout << "hi!" << flush; // flushes the buffer; adds no data
cout << "hi!" << ends; // inserts a null, then flushes the
buffer
cout << "hi!" << endl; // inserts a newline, then flushes the
buffer
unitbuf 操纵符
如果需要刷新所有输出,最好使用 unitbuf 操纵符。这个操纵符在每次执
行完写操作后都刷新流:
cout << unitbuf << "first" << " second" << nounitbuf;
等价于:
cout << "first" << flush << " second" << flush;
nounitbuf 操纵符将流恢复为使用正常的、由系统管理的缓冲区刷新方式。

文件模式

 

对同一个文件作输入和输出运算
fstream 对象既可以读也可以写它所关联的文件。fstream 如何使用它的文
件取决于打开文件时指定的模式。
396
默认情况下,fstream 对象以 in 和 out 模式同时打开。当文件同时以 in
和 out 打开时不清空。如果打开 fstream 所关联的文件时,只使用 out 模式,
而不指定 in 模式,则文件会清空已存在的数据。如果打开文件时指定了 trunc
模式,则无论是否同时指定了 in 模式,文件同样会被清空。下面的定义将
copyOut 文件同时以输入和输出的模式打开:
// open for input and output
fstream inOut("copyOut", fstream::in | fstream::out);

 

文件模式的组合

 

 

实例:

#include <iostream>#include <fstream>int main(int argc, char *argv[]){//fstream inOut("copyOut", fstream::in | fstream::out); //读写操作流string filename = "./haha";char buf[20];ofstream outfile(filename.c_str(), ofstream::out|ofstream::app);if(!outfile){cout<< "open file error\n";}outfile<<"rerwtrgw\n"<<flush;outfile.close();    ifstream infile(filename.c_str(), ifstream::in);if(!infile){cout<< "open file error\n";}while(infile.getline(buf, 20)){cout << buf << endl;}infile.close();infile.clear();    return 0;}


 

0 0
原创粉丝点击