ca76a_c++_流文件打开输入输出文件模式p773

时间:2023-03-09 14:26:00
ca76a_c++_流文件打开输入输出文件模式p773

/*ca76a_c++_流文件打开输入输出文件模式
利用文件流打开文件进行输入与输出时的选项
in、out、app(附加模式)、ate((end)文件打开后,定于文件结尾)、trunc(裁剪)、binary(二进制)、、、、、
文件模式组合
out
out|app
out|trunc
in
in|out
int|out|ate
int|out|trunc

welcome to discuss
txwtech@163.com
*/

 /*ca76a_c++_流文件打开输入输出文件模式
利用文件流打开文件进行输入与输出时的选项
in、out、app(附加模式)、ate((end)文件打开后,定于文件结尾)、trunc(裁剪)、binary(二进制)、、、、、
文件模式组合
out
out|app
out|trunc
in
in|out
int|out|ate
int|out|trunc welcome to discuss
txwtech@163.com
*/
#include <iostream>
#include <fstream>
#include <string> using namespace std; int main()
{
//ifstream读取文件内容
string s;
ifstream ifs("file1.txt",ifstream::in);//不写就是默认的文件模式in打开
//先判断,是否打开成功
if (!ifs)
{
cerr << "打开文件错误." <<"文件:"<<__FILE__<<" "<<__DATE__<< endl;
return -;
}
ifs >> s;
cout << s << endl;
ifs >> s;
cout << s << endl;
ifs.close();
cout << s << endl; //ofstream在没有找到文件时,先创建文件,在写入文件。
ofstream ofs("file11.txt",ofstream::out);//不写就是默认的文件模式out方式创建文件
ofs << "hello file2!" << endl;//写入内容
ofs.close();
//ofs5("file5.txt"),默认就是ofstream::out|ofstream::trunc
ofstream ofs5("file5.txt",ofstream::out);//out是文件内容清空了
ofs5 << "hello55,ok" << endl;//写入内容到文件
ofs5.close();
//向文件末追加信息
ofstream ofs6("file11.txt", ofstream::out | ofstream::app);
ofs6 << "ofs6 added" << endl;
ofs6.close(); //fstream既可以输入可以输出
fstream ofs7("file5.txt", fstream::in | fstream::out);//内容不会清空
//fstream ofs8("file5.txt", fstream::in | fstream::out|fstream::trunc);//会清空内容 ofs7.close();
//ofs8.close();
//打开后,指针定位到文件末尾
fstream ofs9("file5.txt", fstream::in | fstream::out | fstream::ate);
ofs9 << "ofs9 added"; //写入到文件
ofs9.close(); //fstream ofs10("file10.txt", fstream::in | fstream::out );
//fstream,如果没有找到文件,不会自动创建文件。
fstream ofs10("file10.txt", fstream::in | fstream::out | fstream::ate);
if (!ofs10)
{
cerr << "打开文件10错误." << "文件:" << __FILE__ << " " << __DATE__ << endl;
return -;
}
ofs10 << "ofs10 added"; //写入到文件
ofs10.close();
return ;
}