写文件

写文件操作

读写文件的需要用到C++提供的文件流库 fstream。

写文件包含五个步骤

  1. 创建写文件流对象。
  2. 设置文件路径。
  3. 设置写文件打开方式。
  4. 写入。
  5. 关闭文件。

文件的打开方式

  • ios::in:以读方式打开文件
  • ios::out:以写方式打开文件
  • ios::ate:开始位置为文件尾
  • ios::app:以追加方式写文件
  • ios::trunc:如果文件存在先删除文件,再创建文件
  • ios::binary:二进制方式打开文件
#include <iostream>
#include <fstream>

using namespace std;

void test() {
    //创建文件流对象
    ofstream ofs;
    //指定打开文件和打开文件的方式
    ofs.open("test.txt", ios::out);
    //写入内容
    ofs << "写入文件。" << endl;
    //关闭文件
    ofs.close();
}

int main() {
    test();
    return 0;
}

 

posted @ 2023-02-26 18:01  Meetalone  阅读(114)  评论(0编辑  收藏  举报