C++文件操作之写文件

C++文件操作之写文件有五个步骤:

1.包含头文件

#include

 2.创建流对象
 

ofstream ofs;

3.指定打开方式
  

 ofs.open("01.txt", ios::out);

注意:

01.txt是文件路径 

ios::out是打开方式

文件的打开方式有以下六种:

ios::in 为读文件而打开文件
ios::out 为写文件而打开文件
ios::ate 初始位置:文件尾
ios::app 追加方式写文件
ios::trunc 如果文件存在,先删除再创建
ios::binary 二进制形式


4.往文件写内容

ofs << "jack-001" << endl;
 ofs << "tom-002" << endl;

5.关闭文件

    ofs.close();

整体代码:

#include
#include
#include//头文件
using namespace std;
//文本文件--写文件
void test()
{
	//1.包含头文件
	//2.创建流对象
	ofstream ofs;
	//3.指定打开方式
	ofs.open("01.txt", ios::out);
	//4.往文件写内容
	ofs << "jack-001" << endl;
	ofs << "tom-002" << endl;
	//5.关闭文件
	ofs.close();
}
int main()
{
	test();
	system("pause");
	return 0;
}

就会在所写路径下创建出文件

C++文件操作之写文件_第1张图片

双击打开文件:

C++文件操作之写文件_第2张图片

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