文件流fstream和字符串流sstream的使用
来源:互联网 发布:东北大学软件学院宿舍 编辑:程序博客网 时间:2024/06/04 19:03
文件流就是将流与文件进行绑定,读写文件。字符串流就是将流与字符串进行绑定,读写字符串。
文件流类有ifstream,ofstream和fstream,而字符串流类有istrstream,ostrstream和strstream。文件流类和字符串流类都是ostream,istream和iostream类的派生类,因此对它们的操作方法是基本相同的。
以下以实例说明文件流的使用方法:
#include "stdafx.h"#include <string>#include <iostream>#include <fstream>using namespace std;int _tmain(int argc, _TCHAR* argv[]){/***IO标准库使用C风格的字符串而不是C++(string)风格的字符串,故要调用c_str()函数。***///定义流,并绑定相应的文件,如果文件不存在会创建文件 1---------string strfilein = "1.txt",strfileout = "2.txt";//定义读入流并绑定文件,作用:将文件中的数据读入到string等ifstream infile(strfilein.c_str(),ifstream::in|ifstream::binary);//定义写入流并绑定文件,作用:将string的数据读入到文件等//指定app模式,这样打开文件后,文件中原有的数据就不会被删除ofstream outfile(strfileout.c_str(),ofstream::out|ofstream::app);//定义流,并绑定相应的文件,如果文件不存在会创建文件 2---------string strfilein1 = "3.txt",strfileout1 = "4.txt";ifstream infile1; //定义读入流ofstream outfile1; //定义写入流infile1.open(strfilein1.c_str());//读入流绑定文件,使用文件默认的模式outfile1.open(strfileout1.c_str());//写入流绑定文件,使用文件默认的模式//判断文件打开是否成功----------------------if(!infile){cout<<"打开文件失败:infile"<<endl;infile.close(); //关闭流并不能清空流的内部状态infile.clear();//清空流的内部状态}else{cout<<"打开文件成功:infile"<<endl;}if(!outfile){cout<<"打开文件失败:outfile"<<endl;outfile.close(); //关闭流并不能清空流的内部状态outfile.clear();//清空流的内部状态}else{cout<<"打开文件成功:outfile"<<endl;}if(!infile1){cout<<"打开文件失败:infile1"<<endl;infile1.close(); //关闭流并不能清空流的内部状态infile1.clear();//清空流的内部状态}else{cout<<"打开文件成功:infile1"<<endl;}if(!outfile1){cout<<"打开文件失败:outfile1"<<endl;outfile1.close(); //关闭流并不能清空流的内部状态outfile1.clear();//清空流的内部状态}else{cout<<"打开文件成功:outfile1"<<endl;}//将 infile 与新文件重新绑定-----------------infile.close();//首先关闭infileinfile.clear();//清空内部状态infile.open("5.txt");//然后绑定//-------------------------------------------------string strcontent;while (!infile.eof()){infile >> strcontent;//遇到 空格\t、回车\n 结束输入//getline(infile,strcontent);//一次读取文件中的一行outfile << strcontent;//写入到文件里}return 0;}
阅读全文
0 0
- 文件流fstream和字符串流sstream的使用
- C++ 字符串流sstream
- sstream 与 fstream的使用
- 字符串流的使用
- [日常学习][C++]字符串流 <sstream>
- 读取PPM文件源代码(使用了fstream, sstream,string)
- sstream和strstream以及fstream
- C++ stringstream的用法|c++ 字符串流 sstream(常用于格式转换)
- sscanf和sstream的使用
- 从零开始学C++之IO流类库(一):流类库继承体系(IO流,文件流,串流)和 字符串流的基本操作
- 从零开始学C++之IO流类库(一):流类库继承体系(IO流,文件流,串流)和 字符串流的基本操作
- C++ sstream 字符数据流的使用
- c++ 字符串流 sstream(常用于格式转换)
- c++ 字符串流 sstream(常用于格式转换)
- c++ 字符串流 sstream(常用于格式转换)
- c++ 字符串流 sstream(常用于格式转换)
- c++ 字符串流 sstream(常用于格式转换)
- c++ 字符串流 sstream(常用于格式转换)
- Python安装第三方库,如何安装.whl和.egg文件
- python的hashlib字符串加密模块
- Swagger2 添加HTTP head参数
- mysql 的使用
- windows10 安装homestead简单记录
- 文件流fstream和字符串流sstream的使用
- Python02_函数
- nginx配置404重定向
- 【PAT】【Advanced Level】1116. Come on! Let's C (20)
- 分治题目
- LInux下如何安装ffmpeg
- vs2008 C++创建和调用标准DLL
- ubuntu 16.04 安装mysqlclient数据库驱动
- 项目重点技术