文本文件操作

 头文件:
#include <fstream>
输出(写操作):ofstream
输入(读操作):ifstream
同时读写:fstream

通过一个流对象(文件在程序中被打开由流对象(所谓的上述几个类的对象)来操作)操作一个文件我们需要用到流对象的成员函数。
在这里插入图片描述
这写所有的标识符可以用过 | 自由组合产生不一样的效果!
三种类对文件进行打开操作时都分别有各自的默认打开方式,如果没有提前声明打开方式将会是默认打开方式;
在这里插入图片描述
文本文件操作的类是从ostream、istream、iostream引申而来的,这也就说明fstream的对象可以使用其父类的成员来访问数据;

使用重载插入操作符<<


// writing on a text file
      #include <fiostream.h>
     
      int main () {
          ofstream examplefile   ("example.txt");
          if (examplefile.is_open()) {
              examplefile <<   "This is a line.\n";
              examplefile <<   "This is another line.\n";
              examplefile.close();
          }
          return 0;
      }
   

文件中读入数据也可以用cin

// reading a text file
      #include <iostream.h>
      #include <fstream.h>
      #include <stdlib.h>
     
      int main () {
          char buffer[256];
          ifstream examplefile   ("example.txt");
          if (! examplefile.is_open())
          { cout << "Error   opening file"; exit (1); }
          while (! examplefile.eof() ) {
              examplefile.getline   (buffer,100);
              cout << buffer   << endl;
          }
          return 0;
      }

状态标志符的验证(Verification of state flags)

除了eof()以外,还有一些验证流的状态的成员函数(所有都返回bool型返回值):

bad()
如果在读写过程中出错,返回 true 。例如:当我们要对一个不是打开为写状态的文件进行写入时,或者我们要写入的设备没有剩余空间的时候。

fail()
除了与bad() 同样的情况下会返回 true 以外,加上格式错误时也返回true ,例如当想要读入一个整数,而获得了一个字母的时候。

eof()
如果读文件到达文件末尾,返回true。

good()
这是最通用的:如果调用以上任何一个函数返回true 的话,此函数返回 false 。

要想重置以上成员函数所检查的状态标志,你可以使用成员函数clear(),没有参数。

获得和设置流指针(get and put stream pointers)

所有输入/输出流对象(i/o streams objects)都有至少一个流指针:

ifstream, 类似istream, 有一个被称为get pointer的指针,指向下一个将被读取的元素。
ofstream, 类似 ostream, 有一个指针 put pointer ,指向写入下一个元素的位置。
fstream, 类似 iostream, 同时继承了get 和 put
我们可以通过使用以下成员函数来读出或配置这些指向流中读写位置的流指针:

tellg() 和 tellp()
这两个成员函数不用传入参数,返回pos_type 类型的值(根据ANSI-C++ 标准) ,就是一个整数,代表当前get 流指针的位置 (用tellg) 或 put 流指针的位置(用tellp).

seekg() 和seekp()
这对函数分别用来改变流指针get 和put的位置。两个函数都被重载为两种不同的原型:

seekg ( pos_type position ); seekp ( pos_type position );

使用这个原型,流指针被改变为指向从文件开始计算的一个绝对位置。要求传入的参数类型与函数 tellg 和tellp 的返回值类型相同。

seekg ( off_type offset, seekdir direction ); seekp ( off_type offset, seekdir direction );

使用这个原型可以指定由参数direction决定的一个具体的指针开始计算的一个位移(offset)。它可以是:在这里插入图片描述
流指针 get 和 put 的值对文本文件(text file)和二进制文件(binary file)的计算方法都是不同的,因为文本模式的文件中某些特殊字符可能被修改。由于这个原因,建议对以文本文件模式打开的文件总是使用seekg 和 seekp的第一种原型,而且不要对tellg 或 tellp 的返回值进行修改。对二进制文件,你可以任意使用这些函数,应该不会有任何意外的行为产生。

使用ifstream和getline读取文件内容:

假设有一个叫 data.txt 的文件, 它包含以下内容:

                        Fry: One Jillion dollars.
 [Everyone gasps.]
 Auctioneer: Sir, that's not a number.
数据读取, 测试 。


以下就是基于 data.txt 的数据读取操作:

#include <iostream>
 #include <fstream>
 #include <string>

 using namespace std;

 //输出空行
void OutPutAnEmptyLine()
 {
     cout<<"\n";
 }

 //读取方式: 逐词读取, 词之间用空格区分
//read data from the file, Word By Word
 //when used in this manner, we'll get space-delimited bits of text from the file
 //but all of the whitespace that separated words (including newlines) was lost.
 void ReadDataFromFileWBW()
 {
     ifstream fin("data.txt");
     string s;
     while( fin >> s )
      {
         cout << "Read from file: " << s << endl;
     }
 }

 //读取方式: 逐行读取, 将行读入字符数组, 行之间用回车换行区分
//If we were interested in preserving whitespace,
 //we could read the file in Line-By-Line using the I/O getline() function.
 void ReadDataFromFileLBLIntoCharArray()
 {
     ifstream fin("data.txt");
     const int LINE_LENGTH = 100;
     char str[LINE_LENGTH];
     while( fin.getline(str,LINE_LENGTH) )
      {
         cout << "Read from file: " << str << endl;
     }
 }

 //读取方式: 逐行读取, 将行读入字符串, 行之间用回车换行区分
//If you want to avoid reading into character arrays,
 //you can use the C++ string getline() function to read lines into strings
 void ReadDataFromFileLBLIntoString()
 {
     ifstream fin("data.txt");
     string s;
     while( getline(fin,s) )
      {
         cout << "Read from file: " << s << endl;
     }
 }

 //带错误检测的读取方式
//Simply evaluating an I/O object in a boolean context will return false
 //if any errors have occurred
 void ReadDataWithErrChecking()
 {
     string filename = "dataFUNNY.txt";
     ifstream fin( filename.c_str());
     if( !fin )
      {
         cout << "Error opening " << filename << " for input" << endl;
         exit(-1);
     }
 }

 int main()
 {
     ReadDataFromFileWBW(); //逐词读入字符串
     OutPutAnEmptyLine(); //输出空行

    ReadDataFromFileLBLIntoCharArray(); //逐词读入字符数组
    OutPutAnEmptyLine(); //输出空行

    ReadDataFromFileLBLIntoString(); //逐词读入字符串
    OutPutAnEmptyLine(); //输出空行

    ReadDataWithErrChecking(); //带检测的读取
    return 0;
 }


输出结果为:
Read from file: Fry:
Read from file: One
Read from file: Jillion
Read from file: dollars.
Read from file: [Everyone
Read from file: gasps.]
Read from file: Auctioneer:
Read from file: Sir,
Read from file: that’s
Read from file: not
Read from file: a
Read from file: number.
Read from file: 数据读取,
Read from file: 测试
Read from file: 。

Read from file: Fry: One Jillion dollars.
Read from file: [Everyone gasps.]
Read from file: Auctioneer: Sir, that’s not a number.
Read from file: 数据读取, 测试 。

Read from file: Fry: One Jillion dollars.
Read from file: [Everyone gasps.]
Read from file: Auctioneer: Sir, that’s not a number.
Read from file: 数据读取, 测试 。

Error opening dataFUNNY.txt for input
Press any key to continue

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值