文档详情

C++读取txt文件.doc

发布:2017-05-18约6.32千字共10页下载文档
文本预览下载声明
? c++学习笔记—c++对txt文件的读取与写入 标签:?c++IO 2015-01-13 17:43?1880人阅读?评论(0)?收藏?举报 ?分类: c/c++编程(8)? 版权声明:本文为博主原创文章,未经博主允许不得转载。 一、文件的输入输出 头文件fstream定义了三个类型支持文件IO:ifstream从给定文件读取数据、ofstream向一个给定文件写入数据、fstream读写给定数据。这些类型与cin和cout的操作一样,我们可以用IO操作符来读写文件,还可以用getline从一个ifstream读取数据。 1、getline()函数 getline的函数原型为: [cpp]?view plain?copy istream?getline(istream??is,?string?str,?char?delim);?? istream?getline(istream?is,?string?str,?char?delim);?? istream?getline(istream??is,?string?str);?? istream?getline(istream?is,?string?str);?? 通常我们使用getline函数读取一整行,该函数接受一个输入流和一个string对象,函数从给定的输入流中读取内容,直到遇到换行符为止,然后将所读的内容存入到个string对象中。 另外,当函数为istream getline (istream is, string str, char delim);形式时,函数遇到delim也会停止。 2、使用文件流对象 当我们想要读入一个文件时,可以定义一个文件流对象,并将对象与文件相关联起来,每一个文件流类都定义了一个名为open的成员函数,完成一系列系统相关的操作。 open函数的原型为: [cpp]?view plain?copy void?open?(const???char*?filename,??ios_base::openmode?mode?=?ios_base::out);?? void?open?(const?string?filename,??ios_base::openmode?mode?=?ios_base::out);?? 文件模式(mode)有一下几种: [cpp]?view plain?copy ofstream?outfile(E:\\out.txt,?ofstream::app);?? 上述代码打开out.txt文件,如果不存在,系统会创建此txt文件,并且定位到文件末尾。 打开的文件使用完成后一定要关闭,fstreamclose()来完成此操作。 例:从hello.txt文件中读取数据并写入到out.txt中 [cpp]?view plain?copy #include?stdafx.h?? #include?vector?? #include?string?? #include?fstream?? #include?iostream?? using?namespace?std;?? int?_tmain(int?argc,?_TCHAR*?argv[])?? {?? ????ifstream?myfile(E:\\hello.txt);?? ????ofstream?outfile(E:\\out.txt,?ofstream::app);?? ????string?temp;?? ????if?(!myfile.is_open())?? ????{?? ????????cout??未成功打开文件??endl;?? ????}?? ????while(getline(myfile,temp))?? ????{?? ????????outfiletemp;?? ????}?? ????myfile.close();?? ????return?0;?? }?? 二、string流 string头文件定义了三个类型来支持内存IO,istringstream向string写入数据,ostringstream从string读取数据,stringstream既可从string读取数据也可向string写数据,就像string是一个IO流一样。 1、istringstream的用法 [cpp]?view plain?copy #include?stdafx.h?? #include?string?? #include?sstream????//使用istringstream所需要的头文件?? #include?iostream?? using?namespace?std;?? int?_tmain(int?argc,?_TCHAR*?argv[])?? {?
显示全部
相似文档