C++文件打开

/*
文件打开有两种基本的方法:
1)<文件流类> <文件流对象名>("路径+文件名.格式",<打开方式>)
例如 fstream myfile("E:\\***\\test.txt", ios::out|ios::in|ios::trunc);不能有中文路径

2)fstream myfile;
myfile.open("E:\\***\\test.txt", ios::out|ios::in|ios::trunc);不能有中文路径

看一下<大开发式>
ios::in 为读打开 文件必须存在否则报错
ios::out 为写打开 覆盖
out|trunc 为写打开 覆盖
out|app 为在文件结尾写而打开 不覆盖
in|out 为输入/输出而打开 文件必须存在否则报错
in|out|trunc为输入/输出而打开 覆盖
in|out|app 为输入/输出而打开 不覆盖,在文件的结尾写

*/

#include<iostream>
#include<fstream>
using namespace std;

int main()
{
fstream myofile;
myofile.open("E:\\zerolearnC++\\container of file\\ypan1.txt", ios::out|ios::trunc); //不认识中文路径?
cout<<"Create file 1"<<endl;
if(!myofile.fail())
{
myofile<<"***** 今天是一个好日子,虽然什么好事都没有发生,但是也没什么糟糕的事情发生。";
myofile<<"不看不知道,一看吓一跳,今天已经10月4号了。时间过得真快,还什么都没有做";
myofile<<",十一就过去了大半。这好比我的人生一样,还什么都没有做,却已经所剩无几了。咳咳咳";
myofile<<",不装逼了。"<<endl;
myofile.close();
}
myofile.open("E:\\zerolearnC++\\container of file\\ypan1.txt",ios::out|ios::in|ios::app);
if(!myofile.fail())
{
myofile<<" "<<"我就是试一下子,看看原来写的有没有被覆盖"<<endl;
myofile.close();
}
return 0;
}

原文地址:https://www.cnblogs.com/emptyYPen/p/5930462.html