一、文件的输入输出

头文件fstream定义了三个类型支持文件IO:ifstream从给定文件读取数据、ofstream向一个给定文件写入数据、fstream读写给定数据。这些类型与cin和cout的操作一样,我们可以用IO操作符来读写文件,还可以用getline从一个ifstream读取数据。

1、getline()函数

getline的函数原型为:

  1. istream& getline(istream&  is, string& str, char delim);
  2. istream& getline(istream&& is, string& str, char delim);
  3. istream& getline(istream&  is, string& str);
  4. istream& getline(istream&& is, string& str);

通常我们使用getline函数读取一整行,该函数接受一个输入流和一个string对象,函数从给定的输入流中读取内容,直到遇到换行符为止,然后将所读的内容存入到个string对象中。

另外,当函数为istream& getline (istream& is, string& str, char delim);形式时,函数遇到delim也会停止。

2、使用文件流对象

当我们想要读入一个文件时,可以定义一个文件流对象,并将对象与文件相关联起来,每一个文件流类都定义了一个名为open的成员函数,完成一系列系统相关的操作。

open函数的原型为:

  1. void open (const   char* filename,  ios_base::openmode mode = ios_base::out);
  2. void open (const string& filename,  ios_base::openmode mode = ios_base::out);

文件模式(mode)有一下几种:

  1. ofstream outfile("E:\\out.txt", ofstream::app);

上述代码打开out.txt文件,如果不存在,系统会创建此txt文件,并且定位到文件末尾。
打开的文件使用完成后一定要关闭,fstream提供了成员函数close()来完成此操作。

例:从hello.txt文件中读取数据并写入到out.txt中

  1. #include "stdafx.h"
  2. #include <vector>
  3. #include <string>
  4. #include <fstream>
  5. #include <iostream>
  6. using namespace std;
  7. int _tmain(int argc, _TCHAR* argv[])
  8. {
  9. ifstream myfile("E:\\hello.txt");
  10. ofstream outfile("E:\\out.txt", ofstream::app);
  11. string temp;
  12. if (!myfile.is_open())
  13. {
  14. cout << "未成功打开文件" << endl;
  15. }
  16. while(getline(myfile,temp))
  17. {
  18. outfile<<temp;
  19. }
  20. myfile.close();
  21. return 0;
  22. }

二、string流

string头文件定义了三个类型来支持内存IO,istringstream向string写入数据,ostringstream从string读取数据,stringstream既可从string读取数据也可向string写数据,就像string是一个IO流一样。

1、istringstream的用法

  1. #include "stdafx.h"
  2. #include <string>
  3. #include <sstream>    //使用istringstream所需要的头文件
  4. #include <iostream>
  5. using namespace std;
  6. int _tmain(int argc, _TCHAR* argv[])
  7. {
  8. string str = "I am a boy";
  9. istringstream is(str);
  10. string s;
  11. while (is >> s)
  12. {
  13. cout << s << endl;
  14. }
  15. return 0;
  16. }

输出结果为:

I

am

a

boy

例:编写程序,将来自一个文件中的行保存在一个vector<string>中,然后使用istringstream从vector读取数据元素,每次读取一个单词。

  1. #include "stdafx.h"
  2. #include <vector>
  3. #include <string>
  4. #include <fstream>
  5. #include <sstream>
  6. #include <iostream>
  7. using namespace std;
  8. int _tmain(int argc, _TCHAR* argv[])
  9. {
  10. vector<string> vec;
  11. ifstream myfile("E:\\hello.txt");
  12. string temp;
  13. if (!myfile.is_open())
  14. {
  15. cout << "未成功打开文件" << endl;
  16. }
  17. while(getline(myfile,temp))
  18. {
  19. vec.push_back(temp);
  20. }
  21. for (auto it = vec.begin(); it != vec.end(); it++)
  22. {
  23. cout << *it << endl;
  24. }
  25. cout << "-----------------使用istringstream------------------------" << endl;
  26. for (auto it = vec.begin(); it != vec.end(); it++)
  27. {
  28. istringstream record(*it);
  29. string s;
  30. while (record >> s)
  31. cout << s << endl;
  32. }
  33. return 0;
  34. }

运行结果如图所示:

//下述论述转自www.cndev-lab.com ,程序作者:管宁

  1. #i nclude <iostream>
  2. #i nclude <sstream>
  3. using namespace std;
  4. int main()
  5. {
  6. istringstream istr;
  7. istr.str("1 56.7",);
  8. //上述两个过程可以简单写成 istringstream istr("1 56.7");
  9. cout << istr.str()<<endl;
  10. int a;
  11. float b;
  12. istr>>a;
  13. cout<<a<<endl;
  14. istr>>b;
  15. cout<<b<<endl;
  16. system("pause");
  17. }

  上例中,构造字符串流的时候,空格会成为字符串参数的内部分界,例子中对a,b对象的输入"赋值"操作证明了这一点,字符串的空格成为了整型数据与浮点型数据的分解点,利用分界获取的方法我们事实上完成了字符串到整型对象与浮点型对象的拆分转换过程。

  str()成员函数的使用可以让istringstream对象返回一个string字符串(例如本例中的输出操作(cout<<istr.str();)。

2、ostringstream的用法

 ostringstream同样是由一个string对象构造而来,ostringstream类向一个string插入字符。 
 ostringstream的构造函数原形如下:

  1. ostringstream::ostringstream(string str);

//下述论述转自www.cndev-lab.com ,程序作者:管宁

  1. #i nclude <iostream>
  2. #i nclude <sstream>
  3. #i nclude <string>
  4. using namespace std;
  5. int main()
  6. {
  7. ostringstream ostr;
  8. //ostr.str("abc");//如果构造的时候设置了字符串参数,那么增长操作的时候不会从结        尾开始增加,而是修改原有数据,超出的部分增长
  9. ostr.put('d');
  10. ostr.put('e');
  11. ostr<<"fg";
  12. string gstr = ostr.str();
  13. cout<<gstr;
  14. system("pause");
  15. }

在上例代码中,我们通过put()或者左移操作符可以不断向ostr插入单个字符或者是字符串,通过str()函数返回增长过后的完整字符串数据,但值 得注意的一点是,当构造的时候对象内已经存在字符串数据的时候,那么增长操作的时候不会从结尾开始增加,而是修改原有数据,超出的部分增长。

c++学习笔记—c++对txt文件的读取与写入的更多相关文章

  1. c# txt文件的读取和写入

    我们在工程实践中经常要处理传感器采集的数据,有时候要把这些数据记录下来,有时候也需要把记录下来的数据读取到项目中.接下来我们用C#演示如何对txt文件进行读写操作.我们要用到StreamReader  ...

  2. C# txt文件的读取与写入

    C#创建记事本方法一://创建对象 FileStream stream = new FileStream(@"d:\aa.txt",FileMode.Create);//fileM ...

  3. 《程序实现》从xml、txt文件里读取数据写入excel表格

    直接上码 import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java ...

  4. (三)C#关于txt文件的读取和写入

    using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Tex ...

  5. c++对txt文件的读取与写入

    转自:http://blog.csdn.net/lh3325251325/article/details/4761575 #include <iostream> #include < ...

  6. c#中对txt文件的读取与写入,针对二维数组

    class Program { ; ; static string[,] str = new string[ROW, COL]; static void Main(string[] args) { R ...

  7. python学习笔记(六)文件夹遍历,异常处理

    python学习笔记(六) 文件夹遍历 1.递归遍历 import os allfile = [] def dirList(path): filelist = os.listdir(path) for ...

  8. java 学习笔记之 流、文件的操作

    ava 学习笔记之 流.文件的操作 对于一些基础的知识,这里不再过多的解释, 简单的文件查询过滤操作 package com.wfu.ch08; import java.io.File; import ...

  9. Java NIO 学习笔记(四)----文件通道和网络通道

    目录: Java NIO 学习笔记(一)----概述,Channel/Buffer Java NIO 学习笔记(二)----聚集和分散,通道到通道 Java NIO 学习笔记(三)----Select ...

随机推荐

  1. e867. 获取和设置外观

    To change the look and feel, you need to know the class name of the new look and feel. This example ...

  2. Mac环境下配置tomcat的步骤详解

    前言 相信对Java Web稍微知道一点,一般对Tomcat都不会陌生,Apache是普通服务器,本身只支持html即普通网页,可以通过插件支持PHP,还可以与Tomcat连通(单向Apache连接T ...

  3. Eclipse/MyEclipse上配置Spring环境

    在MyEclipse上配置Spring环境 myeclipse其实已经集成Spring的开发环境,我们只需在新建的项目上添加spring的配置环境就可以 新建一个java项目 选中创建好的项目之后,在 ...

  4. (转)【多媒体封装格式详解】--- AAC ADTS格式分析

     出自:http://blog.csdn.net/tx3344/article/details/7414543 http://www.it6655.com/2012/08/aac-adts-html ...

  5. 【Access-Control-Allow-Origin】跨域问题

    [前言] 在实际项目中,可能是多个项目共同完成某个功能,他们之间需要实现数据的交互.这样就会需要有跨域的问题. 比如,发布在不同电脑上的不同项目之间,用不同语言开发的项目之间…… [JSONP] 当使 ...

  6. Memcached存储机制

    Memcached存储机制 memcached 内存管理 分析(转) 缓存.缓存算法和缓存框架简介 memcached全面剖析–PDF总结篇

  7. Java并发包学习一 ThreadFactory介绍

    ThreadFactory翻译过来是线程工厂,顾名思义,就是用来创建线程的,它用到了工厂模式的思想.它通常和线程池一起使用,主要用来控制创建新线程时的一些行为,比如设置线程的优先级,名字等等.它是一个 ...

  8. koa2入门学习

    koa模块 koa-route 路由 route.get("路径",路由函数) koa-static 静态资源加载     const serve(路径) koa-compose  ...

  9. 超分辨率论文CVPR-Kai Zhang

    深度学习与传统方法结合的超分辨率:Kai Zhang 1. (CVPR, 2019) Deep Plug-and-Play Super-Resolution for Arbitrary https:/ ...

  10. PHP框架 Yii framework 用yiic命令时提示“php.exe”不是内部或外部命令

    解决方案 yii/framework/yiic.bat,修改 if "%PHP_COMMAND%" == "" set PHP_COMMAND=php.exei ...