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
*/

 1 /*ca76a_c++_流文件打开输入输出文件模式
 2 利用文件流打开文件进行输入与输出时的选项
 3 in、out、app(附加模式)、ate((end)文件打开后,定于文件结尾)、trunc(裁剪)、binary(二进制)、、、、、
 4 文件模式组合
 5 out
 6 out|app
 7 out|trunc
 8 in
 9 in|out
10 int|out|ate
11 int|out|trunc
12 
13 welcome to discuss
14 txwtech@163.com
15 */
16 #include <iostream>
17 #include <fstream>
18 #include <string>
19 
20 using namespace std;
21 
22 int main()
23 {
24     //ifstream读取文件内容
25     string s;
26     ifstream ifs("file1.txt",ifstream::in);//不写就是默认的文件模式in打开
27     //先判断,是否打开成功
28     if (!ifs)
29     {
30         cerr << "打开文件错误." <<"文件:"<<__FILE__<<" "<<__DATE__<< endl;
31         return -1;
32     }
33     ifs >> s;
34     cout << s << endl;
35     ifs >> s;
36     cout << s << endl;
37     ifs.close();
38     cout << s << endl;
39 
40     //ofstream在没有找到文件时,先创建文件,在写入文件。
41     ofstream ofs("file11.txt",ofstream::out);//不写就是默认的文件模式out方式创建文件
42     ofs << "hello file2!" << endl;//写入内容
43     ofs.close();
44     //ofs5("file5.txt"),默认就是ofstream::out|ofstream::trunc
45     ofstream ofs5("file5.txt",ofstream::out);//out是文件内容清空了
46     ofs5 << "hello55,ok" << endl;//写入内容到文件
47     ofs5.close();    
48     //向文件末追加信息
49     ofstream ofs6("file11.txt", ofstream::out | ofstream::app);
50     ofs6 << "ofs6 added" << endl;
51     ofs6.close();
52 
53 
54 
55     //fstream既可以输入可以输出
56     fstream ofs7("file5.txt", fstream::in | fstream::out);//内容不会清空
57     //fstream ofs8("file5.txt", fstream::in | fstream::out|fstream::trunc);//会清空内容
58 
59     ofs7.close();
60     //ofs8.close();
61     //打开后,指针定位到文件末尾
62     fstream ofs9("file5.txt", fstream::in | fstream::out | fstream::ate);
63     ofs9 << "ofs9 added"; //写入到文件
64     ofs9.close();
65 
66 
67     //fstream ofs10("file10.txt", fstream::in | fstream::out );
68     //fstream,如果没有找到文件,不会自动创建文件。
69     fstream ofs10("file10.txt", fstream::in | fstream::out | fstream::ate);
70     if (!ofs10)
71     {
72         cerr << "打开文件10错误." << "文件:" << __FILE__ << " " << __DATE__ << endl;
73         return -1;
74     }
75     ofs10 << "ofs10 added"; //写入到文件
76     ofs10.close();
77     return 0;
78 }

 

原文链接: https://www.cnblogs.com/txwtech/p/12296706.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

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

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/328567

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月1日 下午4:45
下一篇 2023年3月1日 下午4:45

相关推荐