文件的读写

  1. 需要用到的库
    #include <fstream>
    
  2. **三个用到的可以直接实例化的类
    ifstream//用来完成文件的读操作
    ofstream//用来完成文件的写操作
    fstream//前两者的功能都有
    
  3. open()函数,三个类(ifstream,ofstream,fstream)共有的一个成员函数
    char data[50];
     //从文件读数据
     ifstram rfile;//rfile是ifstream类实力文化后的对象
     rfile.open("kaka.dat");//rfile开始代表“kaka.dat
     rfile >> data;//将文件中的数据放入数组data中
     cout << data << endl;//在屏幕上显示
     rfile.close();//关闭文件
    
    
     //open的几种打开方式
     rfile.open("kaka.dat",ios::app);//单一的追加模式(新信息写入文件末尾)
     rfile.open("kaka.dat",ios::in | ios::out);//双重模式,in是读取,out是写入
     rfile.open("kaka.dat",ios::app | ios::trunc | ios::ate);//三重模式,依次为追加模式,覆写模式,定位到文件末尾
    
  4. 文件位置指针 使用ofstream,ifstream的成员函数seekg()函数
     file.seekg(n);//定位到第n个字节
     file.seekg(n,ios::beg);//默认模式,与前一个功能相同,从文件开始位置向后移动n个字符
     file.seekg(n,ios::cur);//从文件当前位置向后移动n个字节
     file.seekg(0,ios::end);//定位到文件末尾
     file.seekg(n,ios::end);//从文件末尾向前移动n个字节
    
  5. 具体实现
#include <fstream>
#include <iostream>
using namespace std;
 
int main ()
{
    
   char data[100];
 
   // 以写模式打开文件
   ofstream outfile;
   outfile.open("afile.dat");
 
   cout << "Writing to the file" << endl;
   cout << "Enter your name: "; 
   cin.getline(data, 100);
 
   // 向文件写入用户输入的数据
   outfile << data << endl;
 
   cout << "Enter your age: "; 
   cin >> data;
   cin.ignore();
   
   // 再次向文件写入用户输入的数据
   outfile << data << endl;
 
   // 关闭打开的文件
   outfile.close();
 
   // 以读模式打开文件
   ifstream infile; 
   infile.open("afile.dat"); 
 
   cout << "Reading from the file" << endl; 
   infile >> data; 
 
   // 在屏幕上写入数据
   cout << data << endl;
   
   // 再次从文件读取数据,并显示它
   infile >> data; 
   cout << data << endl; 
 
   // 关闭打开的文件
   infile.close();
 
   return 0;
}

本文章使用limfx的vscode插件快速发布