设为首页 加入收藏

TOP

C++学习笔记之输入、输出和文件(二)
2015-07-20 17:56:37 来源: 作者: 【 】 浏览:8
Tags:学习 笔记 输入 输出 文件
5 …… ?// 访问文件“myfile1”
6?
7 ofile . close ( ) ; ?// 关闭文件“myfile1”
8?
9 ofile . open ( "myfile2" ) ?; ? // 重用ofile流
复制代码
?
?
四、文件读写
?
文本文件的读写:
?
方法get(char&)和get()提供不跳过空白的单字符输入功能;
?
方法put(char&)和put()提供不跳过空白的单字符输出功能;
?
函数get(char*,int,char)和getline(char*,int,char)在默认情况下读取整行;
?
二进制文件的读写:
?
二进制文件的读/写分别用成员函数read( )、write( )实现。
写二制文件的格式,输出文件流对象.write((char*)&对象或&对象数组名[下标],sizeof(对象名或所属类名));
读二进制文件的格式,输入文件流对象.read((char*)&对象或&对象数组名[下标],sizeof(对象名或所属类名));
?
使用格式控制(关于格式控制可以参考http://wonderow.cnblogs.com/archive/2005/06/21/178719. html,写得很详细)建立的文本文件:
复制代码
?1 #include
?2 #include
?3?
?4 using namespace std;?
?5?
?6?
?7 int main ()
?8 {?
?9 ? ?ofstream ?ost ;
10 ? ?ost.open ( "d:\\my2.dat" ) ;
11 ? ?ost << "1234567890" << endl ;
12 ? ?int ?a = 123 ;
13 ? ?ost << a << endl ;
14 ? ?ost << setw ( 10 ) << a << endl ;
15 ? ?ost << resetiosflags ( ios :: right ) << setiosflags ( ios :: left )
16 ? ? ? ? << setfill ( '#' ) << setw ( 10 ) << a << endl ;
17 ? ?ost << resetiosflags ( ios :: left ) << setiosflags ( ios :: right )
18 ? ? ? ? << setprecision ( 5 ) << setw ( 10 ) << 12.34567890 << endl ;
19 ? ?ost . close ( ) ;
20 ? ?return 0;
21 }
复制代码
建立一个包含学生学号、姓名、成绩的文本文件:
?
复制代码
?1 #include
?2 #include
?3 #include
?4?
?5 using namespace std;
?6?
?7 int main()
?8 {?
?9 ? ?char fileName[30] , name[30] ; ? ?
10 ? ?int number , score ;
11?
12 ? ?ofstream outstuf; ? ?//建立输出流对象
13?
14 ? ?cout << "Please input the name of students file :\n" ;
15 ? ?cin >> fileName ; ? ?//输入文件名
16?
17 ? ?outstuf.open(fileName, ios::out) ; //以输出方式打开文件
18?
19 ? ?if ( !outstuf )
20 ? ?{?
21 ? ? ? cerr << "File could not be open." << endl ; ??
22 ? ? ? exit(1); ?
23 ? ?}
24 ? ? ? outstuf << "学生成绩文件\n" ;
25 ? ? ? cout << "Input the number, name, and score : (Enter Ctrl-Z to end input)\n? " ;// windows中Ctrl-Z 结束输入和输出
26?
27 ? ?while( cin >> number >> name >> score )?
28 ? ? {?
29 ? ? ? ?outstuf << number << ' ' << name << ' ' << score << '\n' ; ? ?
30 ? ? ? ?cout << "? " ;
31 ? ? } ?
32 ? ?outstuf.close() ;
33 ? ?return 0;
34 }
复制代码
二进制文件,从一个学校教程里搜罗的图
?
?
?
?
?
?
?
五、总结
?
istream类定义了多个版本的抽取运算符(>>),用于识别所有基本的C++类型,并将字符输入转换为这些类型。get()方法族和getline()方法为单字符输入和字符串输入提供了进一步支持;
ostream类定义了多个版本的插入运算符(>>),用于识别所有基本的C++类型,并将字符输入转换为这些类型输出。put()方法为单字符输入和字符串输入提供了进一步支持;
使用ios_base类方法以及文件iostream和iomanip中定义的控制符(参考http://wonderow.cnblogs.com/archive/2005/06/21/178719.html)可以控制格式化输出;
对文件操作,必须将文件与流关联起来,通过ifstream对象与文件关联,可以使用所有istream方法来读取文件,使用ofstream对象与文件关联起来,可以使用ofstream方法来写文件,使用fstream对象关联文件,可以将fstream的输入和输出方法用于文件;
要将文件与流关联,先创建一个文件流对象,然后用open()方法将这个流与文件关联,close()方法终止流与文件的关联;
文本文件是以字符格式存储信息,例如数字值将会被转变为字符表示;
seekg()和seekp()通过指针提供对文件的随机存取。tellg()和tellp()方法报告当前文件的位置;
?
首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇hdu 3221 Brute-force Algorithm(.. 下一篇POJ1456Supermarket(贪心+优先队..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: