st.txt"); if(!inFile) { cout<<"open test.txt failed..."<
获取文件的全部内容的seekg和tellg
为了对文件高效的操作时常要用到文件流的定位功能,在ios_base类中,定义了如下的成员,
typedef _Ios_Seekdir seekdir;
static const seekdir beg = _S_beg; //文件流开头
static const seekdir cur = _S_cur; //当前所在文件流的位置
static const seekdir end = _S_end; //文件流尾部
在istream中定义了tellg和seekg,ostream中定义了tellp和seekp,分别用来获取当前操作所在文件流的位置和进行文件流的操作的定位。如下是通过seek操作来读取整个文件的内容到内存中:
#include
#include
int main () { std::ifstream is ("test.txt", std::ios_base::binary); if (is) { //获取文件的大小 is.seekg (0, std::ios_base::end); //定位到文件结尾 int length = is.tellg(); //获取当前所在文件流的位置,由于已经定位文件结尾,所以是获取文件流大小 is.seekg (0, is.beg); //重新将pos定位到文件流开始 char * buffer = new char [length]; is.read (buffer,length); is.close(); // 输出到屏幕 std::cout.write (buffer,length); delete[] buffer; } return 0; }
内存数据的 I/O操作
C++ I/O标准库支持内存数据的I/O的操作,在sstream头文件中定义了 istringstream,ostringstream,stringstream,只需要将流与内存string对象绑定,就可以进行I/O操作。上面三个I/O类分别用来读取内存string对象到指定对象中,将指定对象中的数据写写入string对象,stringstream可用来读写string对象。
在上面I/O文件操作一节已经说了在istream和ostream中定义的标准输入输出操作,由派生关系可知,对于istringstream,ostringstream同样可以进行标准输入输出操作,对stringstream的stringbuf进行操作(与iostream的streambuf,fstream的filebuf类似,这里暂不介绍)。对于stringstream类常用的操作如下:
stringstream ss(mystr)//创建ss对象,stream流中存放string类型的mystr的数据;
ss.str() //返回ss流中的数据,返回类型为string类型
ss.str(mystr) //设置ss流中数据为mystr的内容
具体使用如下:
#include
#include
#include
using namespace std; int main() { istringstream istream; istream.str("1 2 3 hello"); int a, b, c; string str1; istream>>a>>b>>c>>str1; //从流中读取数据到对象中(以空白符为分割符) cout<