• C++:文件的输入和输出


    1、共同的打开文件方式:

    fin.open("test.txt",ios::binary)
    fout.open("test.txt",ios::binary)
    fboth.open("test.txt",ios::in|ios::out|ios::binary)
    或者
    fistream fin("test.txt",ios::binary)
    fostream fout("test.txt",ios::binary)
    fstream fboth("test.txt",ios::in|ios::out|ios::binary)

    二进制文件的读写
    第一种方式:使用函数get和put
    1.例如 fout.put(ch)
    fin.get(ch)

    //练习1 将a到z的26个字符写到E:\C++\file2.txt中,并读取出来

    #include<iostream>
    #include<fstream>
    using namespace std;
    
    //往文件写入数据 
    void filefout()
    {
      //ofstream fout("E:\C++\file2.txt",ios::binary); 
      ofstream fout;
      fout.open("E:\C++\file2.txt",ios::binary);
      if(!fout)
      {
       cout<<"the write file can not open";
       exit(1); 
      }
      char ch='a';
      for(int i=0;i<26;i++)
      {
       fout.put(ch);
       ch++;
      }
      fout.close();
    } 
    
    //从文件读取数据 
    void filefin()
    {
     ifstream fin;
     fin.open("E:\C++\file2.txt",ios::binary);
     if(!fin)
     {
       cout<<"the read file can not open";
       exit(1);  
     }
     char ch;
     
     while(fin.get(ch))
      cout<<ch;
     /*
     while(!fin.eof())
     {
      fin.get(ch);
      cout<<ch;
     }
     */
     fin.close();
     cout<<endl;
    }
    
    int main()
    {
     filefout();
     filefin();
     return 0;
    }
    /*
    abcdefghijklmnopqrstuvwxyz
    */

    第二种方式:使用read函数和write函数 
    2.例如 fin.read(char*buf,int len)
    fout.write(char*buf,int len)

    练习2:将两门课程名和成绩以二进制的形式存储在E:\C++\file3.txt中,并读取出来

    #include<iostream>
    #include<fstream>
    using namespace std;
    struct list
    {
     char course[15];
     int score;
    };
    
    //往文件中写入数据
    void filewrite()
    {
     list list[2]={"Computer",90,"Math",78};
     ofstream fout("E:\C++\file3.txt",ios::binary);
     if(!fout)
     {
      cout<<"The write file can not open!
    ";
      abort();//exit(1) 
     }
     for(int i=0;i<2;i++)
     {
      fout.write((char*)&list[i],sizeof(list[i]));
     }
     fout.close();
    } 
    
    //从文件读取数据
    void fileread()
    {
     list list[2];    
     ifstream fin("E:\C++\file3.txt",ios::binary);
     if(!fin)
     {
      cout<<"The read file can not open!
    ";
      exit(1);
     }
     for(int i=0;i<2;i++)
     {
      fin.read((char*)&list,sizeof(list[i]));
      cout<<list[i].course<<" "<<list[i].score<<endl;;
     }
     fin.close();
    } 
    
    int main()
    {
     filewrite();
     fileread();
     return 0;
    }
    /*
    Computer 90
    Math 78
    请按任意键继续. . .
    */

    2、在头文件fstream.h中:
    类名 说明 功能
    ifstream 输入文件流类 用于文件的输入
    ofstream 输出文件流类 用于文件的输出
    fstream 输入输出流类 用于文件的输入/输出

    建立流对象,例如
    ifstream fin
    ofstream fout
    fstream fboth


    打开文件方式有两种:
    (1)使用成员函数open打开文件
    文件流对象.open(文件名,打开模式)
    例如:fin.open("test.txt",ios::in)===fin.open("test.txt")
    fboth.open("test.txt",ios::in|ios::out|ios::binary)
    打开模式例如:ios::in输入操作、ios::out输出操作、ios::binary二进制模式 输入输出模式一般会按流对象进行默认

    (2)定义文件流对象时指定参数,通过调用文件流类的构造函数打开文件
    例如:ofstream fout("test.txt").....

    判断读写文件是否成功?
    判断条件:文件打开失败,与文件相关联的流对象的值是0;否则是1.
    例如:if(!fout)
    {
          cout<<"Cannot open file! ";
          //return 1;
    }

    关闭文件:fout.close();

    练习1:先建立一个输出文件,向它写入数据,然后关闭文件,在按输入模式打开它,并读取信息。 

    #include<iostream>
    #include<fstream>
    using namespace std;
    int main()
    {
     //往文件写入数据    
     ofstream fout("E:\C++\file1.txt");//ofstream fout("E:\C++\file1.txt","ios:out");
     if(!fout)                           //如果文件打开失败,fout返回0 
     {
       cout<<"Cannot open file!
     ";
       return 1;
     }
     fout<<"Hello world!
    ";            //将一个字符串写到文件中 
     fout<<100<<' '<<hex<<100<<endl;    //将一个十进制的100,分别以十进制格式和二进制格式写到文件中 
     
     fout.close();                      //关闭写入流 
    
    //从文件读取数据 
    ifstream fin("E:\C++\file1.txt"); //ifstream fin("E:\C++\file1.txt","ios::in")
    if(!fin)                            //如果文件打开失败,fin返回0 
     {
       cout<<"Cannot open file!
     ";
       return 1;
     }
     char buffer[15];                      //定义一个存储数据的字符数粗缓冲区  
     while(!fin.eof())
     {     
      fin.getline(buffer,15);              //一行一行读取数据 
      cout<<buffer<<endl;
     }
    /*
    while(!fin.eof())
    {
     cout<<ch;
     fin.get(ch);
    }
    */
     fin.close();                           //关闭读取流 
     
     return 0; 
    }

    3、

    (1). 检测文件结束EOF(end of file) 采用文件流方式读取方式时,使用成员函数eof(),可以检测这个结束符。
    如果该函数的返回值非0,表示到达文件尾;返回值为0,表示未到达文件末尾。
    例如: ifstream fin;
           ....
    if(!fin.eof()) //尚未到达文件末尾
    {
           ...
    }

    或者
    ifstream fin;
    ....
    if(!fin) //尚未到达文件末尾
    {
           ...
    }

    或者
    这种方式最常用:while(fin.get(ch))
    cout.put(ch);//cout<<ch<<endl;


    (2).二进制文件的随机读取

    类istream提供了3个成员函数来对读指针进行操作:
    tellg() //返回输入文件读指针的当前位置
    seekg(文件中位置) //将输入文件中读指针移动指定的位置
    seekg(位移量,参照位置) //以参照位置为基准,移动若干字节

    文件中位置和位移量都是long型整数,以字节为单位,
    参照位置 ios::beg //从文件开头计算要移动的字节数
    ios::cur //从文件指针的当前位置计算要移动的字节数
    ios::end //从文件末尾指针要移动的字节数

    例如 fin.seekg(-/+50,ios::cur) //从文件指针当前位置向前/向后移动50个字节


    类ostream提供了3个成员函数来对写指针进行操作:
    tellp() //返回输出文件写指针的当前位置
    seekp(文件的位置) //将输出文件中写指针移动到指定的位置
    seekp(位移量,参照位置) //以参照位置为基准移动的若干字节

    练习:随机访问二进制数据文件
    有3门课程的数据,要求:
    (1)以读写方式打开一个磁盘文件,并把这些数据存储到磁盘文件E:\C++\file4.txt;
    (2)将文件指针定位到第3门课程,读取第3门课程的数据并显示出来;
    (3)将文件指针定位到第1门课程,读取第1门课程的数据并显示出来;

    #include<iostream>
    #include<fstream>
    using namespace std;
    struct List
    {
     char course[15];
     int score;
    };
    int main()
    {
     List list[3]={{"Computer",98},{"Math",78},{"Chinese",100}};
     List st;
     fstream fboth;
     fboth.open("E:\C++\file4.txt",ios::out|ios::in|ios::binary);
     if(!fboth)
     {
      cout<<"The read-write file can not open!
    ";
      abort();
     }
     for(int i=0;i<3;i++)
     {
      fboth.write((char*)&list[i],sizeof(List));
     }
     //定位指针到第3门课程
     fboth.seekg(sizeof(List)*2);
     fboth.read((char*)&st,sizeof(List));
     cout<<st.course<<"	"<<st.score<<endl;
     
     //定位指针到第1门课程
     fboth.seekg(sizeof(List)*0);
     fboth.read((char*)&st,sizeof(List));
     cout<<st.course<<"	"<<st.score<<endl;  
     
     //定位指针到下一门课程
     fboth.seekg(sizeof(List)*1,ios::cur);
     fboth.read((char*)&st,sizeof(List));
     cout<<st.course<<"	"<<st.score<<endl; 
     
     fboth.close();
     
     return 0;
    }


    (4)将文件指针定位从当前位置定位到下一门课程,读取该门课程的数据并显示出来;

  • 相关阅读:
    KMP的next[]数组
    [Gauss]HDOJ3976 Electric resistance
    [Gauss]POJ2065 SETI
    [Gauss]POJ2947 Widget Factory
    更好的 SQL 模式的 10 条规则
    BZOJ2460: [BeiJing2011]元素
    BZOJ2115: [Wc2011] Xor
    洛谷P3164 [CQOI2014]和谐矩阵
    POJ1222熄灯问题
    POJ1830开关问题
  • 原文地址:https://www.cnblogs.com/XYQ-208910/p/4912850.html
Copyright © 2020-2023  润新知