zoukankan      html  css  js  c++  java
  • 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();   //没有参数

  • 相关阅读:
    拓扑排序笔记
    Codeforces Round #683 (Div. 2, by Meet IT)(A->C)(构造,思维,贪心)
    Acwing 846. 树的重心(DFS枚举删除每一个点)
    Acwing 125. 耍杂技的牛(贪心)(从局部到全局)
    Acwing 802. 区间和(下标离散化+vector+二分)
    Acwing 799. 最长连续不重复子序列(双指针)
    Acwing 139. 回文子串的最大长度(前缀+后缀处理+哈希+二分)
    Linux shell 变量$#,$@,$0....的含义
    一双不锈钢筷子 的测试用例?
    OSI模型 TCP/IP模型 再整理
  • 原文地址:https://www.cnblogs.com/brillant-ordinary/p/9612734.html
Copyright © 2011-2022 走看看