码迷,mamicode.com
首页 > 编程语言 > 详细

C++ IO学习

时间:2017-03-05 19:25:58      阅读:249      评论:0      收藏:0      [点我收藏+]

标签:文件   类型   参数传递   ifstream   文件中   传递   std   close   string   

关于IO,主要有这么三种类型:标准输入输出,文件输入输出,字符串流。后面两种都是继承自第一种标准输入输出的。他们分别对应的头文件是:

标准输入输出:#include <iostream>

文件输入输出:#include <fstream>

字符串流:#include <sstream>

流对象是不能复制和拷贝的。因此流对象不能用于赋值和参数传递,如果一定要传递,那么必须传递指针或者引用。

这里记录了一个例子来说明,流对象的使用,通过这个使用,来说明流对象的属性状态。上代码,假如在本地D盘根目录下有个文件hello.txt。文件中的内容是001--006。

 1 #include "stdafx.h"
 2 #include <fstream>
 3 #include <sstream>
 4 #include <iostream>
 5 
 6 using namespace std;
 7 
 8 
 9 ifstream &print(ifstream &in)
10 {
11     string str;
12 
13     cout << in.bad() << endl;
14     cout << in.good() << endl;
15     cout << in.fail() << endl;
16     cout << in.eof() << endl;
17     cout << "--------------------1" << endl;
18     while (in >> str)
19     {
20         cout << str << endl;
21     }
22     cout << "--------------------2" << endl;
23     cout << in.bad() << endl;
24     cout << in.good() << endl;
25     cout << in.fail() << endl;
26     cout << in.eof() << endl;
27     cout << "--------------------3" << endl;
28     in.clear();
29     cout << in.bad() << endl;
30     cout << in.good() << endl;
31     cout << in.fail() << endl;
32     cout << in.eof() << endl;
33     in.seekg(0, ios_base::beg);
34     return in;
35 }
36 
37 int main()
38 {
39     ifstream in("d://hello.txt");
40     string str;
41     print(in);
42     while (in >> str)
43     {
44         cout << str << endl;
45     }
46     in.close();
47     return 0;
48 }

 

如上代码示例了读取一个文件,并将文件内容打印到控制台上,并且将IO流重置,并且重新打印一遍。 

其中如下代码表示了流对象的四种状态:

in.bad() 如果流被破坏,则返回true.
in.good()如果流处于有效状态,则返回true。
in.fail() 如果IO操作失败,则返回true。
in.eof() 如果读取文件到了文件末尾,则返回true。
in.clear(); 用于重置所有的状态。
in.seekg(0, ios_base::beg); 将文件操作的指针重置到文件开始处。


技术分享












 

C++ IO学习

标签:文件   类型   参数传递   ifstream   文件中   传递   std   close   string   

原文地址:http://www.cnblogs.com/lucy-lizhi/p/6506261.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!