C++ I/O标准库
2013-08-07 17:58
183 查看
C++学习:
返回指向函数的指针:
int (*ff(int))(int *,int)
想写好这样的代码很难,含义:首先将ff声明为一个函数,它带有一个int形参。该函数返回
int (*)(int* ,int) 这是指向函数的指针,所指向的函数返回int型,并带有两个形参,如果使用
typedf可以简化该函数
typedf int (*PF)(int *,int)
PF ff(int)
今天主要是看了I/o标准库,也就是标准输入输出流,
几个比较经典的例子:
1、检查文件打开是否成功,经常用到:
if( !file){
cerr<<"open failed"<<file<<endl;
return -1
}
2、清除文件流状态
程序要打开多个文件中储存的数据进行处理
while (it !=file.end()){
ifstream input(it->c_str());
if(!input)
break;
while(input >>s)\
process(s);
++it;
}
3、流状态控制
int ival;
while(cin>>ival, !cin.eof()){
if(cin.bad())
throw runtime_error("IO error");
if(cin.fail()){
cerr<<"bad data"
cin.clear(istream::failbit);//重置流
continue;
}
}
几个文件模式:
in 读操作
out 写操作
app 写之前找到文件末尾
ate 打开文件立即定位到文件末尾
trunc 打开文件清空已存在的文件流
binary 二进制文件流
使用方法:
ofstream file("file",ofstream::out | ofstream::trunc)
读写模式打开:fstream file("filename",fstream::in | fstream::out)
返回指向函数的指针:
int (*ff(int))(int *,int)
想写好这样的代码很难,含义:首先将ff声明为一个函数,它带有一个int形参。该函数返回
int (*)(int* ,int) 这是指向函数的指针,所指向的函数返回int型,并带有两个形参,如果使用
typedf可以简化该函数
typedf int (*PF)(int *,int)
PF ff(int)
今天主要是看了I/o标准库,也就是标准输入输出流,
几个比较经典的例子:
1、检查文件打开是否成功,经常用到:
if( !file){
cerr<<"open failed"<<file<<endl;
return -1
}
2、清除文件流状态
程序要打开多个文件中储存的数据进行处理
while (it !=file.end()){
ifstream input(it->c_str());
if(!input)
break;
while(input >>s)\
process(s);
++it;
}
3、流状态控制
int ival;
while(cin>>ival, !cin.eof()){
if(cin.bad())
throw runtime_error("IO error");
if(cin.fail()){
cerr<<"bad data"
cin.clear(istream::failbit);//重置流
continue;
}
}
几个文件模式:
in 读操作
out 写操作
app 写之前找到文件末尾
ate 打开文件立即定位到文件末尾
trunc 打开文件清空已存在的文件流
binary 二进制文件流
使用方法:
ofstream file("file",ofstream::out | ofstream::trunc)
读写模式打开:fstream file("filename",fstream::in | fstream::out)
相关文章推荐
- C++新标准库 VS C++旧标准库 VS 对C库的兼容
- [C/C++标准库]_[初级]_[如何实现std::string自己的Format(sprintf)函数]
- C++库介绍-标准库、类库
- C++ PRIMER之3 标准库类型
- C++ 有名库的介绍, 准标准库Boost
- 一本超越期待的 C++ 书——简评《Boost程序库完全开发指南:深入C++“准”标准库》
- [C/C++标准库]_[初级]_[利用floor进行小数的四舍五入计算]
- c/c++标准库-stdlib.h
- C++ 标准库 string类型(一)
- c++中的标准库类型vector
- C++ 中标准库 map 和 hash_map 的使用方法
- c++ 标准库的各种容器(vector,deque,map,set,unordered_map,unordered_set,list)的性能考虑
- C++中的标准库模板STL
- [C/C++标准库]_[初级]_[优先队列priority_queue的使用]
- [C/C++标准库]_[初级]_[使用auto_ptr智能指针]
- 【C++学习笔记】标准库容器Vector可变长度实现原理
- [C/C++标准库]_[初级]_[构造文件路径(stringByAppendingPathComponent)]
- 简明python教程 --C++程序员的视角(八):标准库
- windows核心编程-C/C++标准库与多线程
- [C/C++标准库]_[初级]_[使用时间库]