C++文件读写操作

读写操作流程:

  1.为要进行操作的文件定义一个流对象。

  2.打开(建立)文件。

  3.进行读写操作。

  4.关闭文件。

详解:

  1.建立流对象:

    输入文件流类(执行读操作):ifstream  in;

    输出文件流类(执行写操作):ofstream  out;

    输入输出文件流类:fstream both;

  注意:这三类文件流类都定义在fstream中,所以只要在头文件中加上fstream即可。

  2.使用成员函数open打开函数:

    使用方式:       ios::in                       以输入方式打开文件(读操作)

                ios::out        以输出方式打开文件(写操作),如果已经存在此名字的文件夹,则将其原有内容全部清除

                ios::app                    以输入方式打开文件,写入的数据增加至文件末尾

                ios::ate                     打开一个文件,把文件指针移到文件末尾

                  ios::binary                 以二进制方式打开一个文件,默认为文本打开方式

    举例:定义流类对象:ofstream out   (输出流)

          进行写操作:out.open("test.dat", ios::out);            //打开一个名为test.dat的问件

  3.文本文件的读写:

    (1)把字符串 Hello World 写入到磁盘文件test.dat中

      

#include<iostream>
#include<fstream>
using namespace std;

int main()
{
  ofstream fout("test.dat", ios::out);
  if(!fout)
  {
       cout<<"文件打开失败!"<<endl;
       exit(1);
  } 
  fout<<"Hello World";
  fout.close();
  return 0;  
}                            检查文件test.dat会发现该文件的内容为 Hello World

    

    (2)把test.dat中的文件读出来并显示在屏幕上

#include<iostream>
#include<fstream>
using namespace std;

int main()
{
  ifstream fin("test.dat", ios::in);
  if(!fin)
  {
       cout<<"文件打开失败!"<<endl;
       exit(1);
  } 
  char str[50];
  fin.getline(str, 50)
  cout<<str<<endl;
  fin.close();
  return 0;  
}                           

  4.文件的关闭:

    流对象.close();   //没有参数

猜你喜欢

转载自www.cnblogs.com/brillant-ordinary/p/9612734.html