c++文件操作

程序运行时产生的数据都属于临时数据,程序一旦运行结束都会被释放。
通过文件可以将数据持久化
c++中对文件操作需要包含头文件****

文件类型分两种:

  1. 文本文件-文件以文本的ASCII码形式存储在计算机中。
  2. 二进制文件-文件以文本的二进制形式存储在计算机中,用户一般读不懂。

操作文件的三大类:

  1. ofstream:写操作 output 从程序传到文件
  2. ifstream: 读操作
  3. fstream: 读写操作

1文本文件

1.1写文件

步骤:

  1. 包含头文件: #include< fstream>
  2. 创建流对象:ofstream ofs;
  3. 打开文件: ofs.open("文件路径“,打开方式);
  4. 写数据: ofs<<"写入的数据“;
  5. ofs.close();

文件打开方式:
c++文件操作_第1张图片

注意: 文件打开方式可以配合使用,利用操作符。
**例如:**用二进制写文件:ios::binary | ios::out

#include 
#include "fstream"
using namespace std;
void test01(){
    ofstream ofs;
    ofs.open("test.txt",ios::out);
    ofs<<"张三"<<endl<<"男"<<endl;
    ofs.close();
}
int main() {
test01();
    return 0;
}

1.2读文件

读文件和写文件步骤相似,但读取的方式比较多。

步骤:

  1. 包含头文件: #include< fstream>
  2. 创建流对象:ifstream ifs;
  3. 打开文件并判断文件是否打开成功: ifs.open("文件路径“,打开方式);
  4. 读数据: 四种方式读取
  5. ifs.close();
#include 
#include "fstream"
#include "string"
using namespace std;
//文本文件-读文件
void test01()
{
    ifstream ifs;
    ifs.open("test.txt",ios::in);
    if(!ifs.is_open())
    {
        cout<<"文件打开失败!"<<endl;
        return;
    }
    //读数据
    //第一种
//    char buf[1024]={0};
//    while(ifs>>buf)
//    {
//        cout<
//    }
    //第二种
//    char buf[1024]={0};
//    while (ifs.getline(buf,sizeof(buf)))
//    {
//        cout<
//    }
//    ifs.close();
    //第三种
//    string buf;
//    while (getline(ifs,buf))
//    {
//        cout<
//    }
    //第四种(不太推荐)
    char c;
    while ((c=ifs.get())!=EOF) //end of file
    {
        cout<<c;
    }
}
int main()
{
    test01();
}

你可能感兴趣的:(c++,c++,开发语言)