• 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();   //没有参数

  • 相关阅读:
    python 入门
    element 使用问题总结
    element dialog 弹窗 解决每次先加载上一次数据再加载本次数据问题
    JS 对变量进行全文替换方法
    react源码解析10.commit阶段
    react源码解析9.diff算法
    react源码解析8.render阶段
    react源码解析7.Fiber架构
    react源码解析6.legacy模式和concurrent模式
    react源码解析5.jsx&核心api
  • 原文地址:https://www.cnblogs.com/brillant-ordinary/p/9612734.html
Copyright © 2020-2023  润新知