文件流

文件流包括ifstream,ofstream,fstream.

 

文件的打开命令:open(char *,ios::out ,int)(文件名,文件打开模式,保护模式)

ofstream文件流对象内有一个子对象,filebuf文件流缓冲区。

如何判断open命令成功is_open(),good(),if(fout),如果文件打开成功,返回文件流缓冲区状态。建议使用assert(fout)的方法进行检测文件打开状态。

为什么一个流对象可以直接作为一个if的判断语句呢?因为在C++内部,将其自动转换为一个流状态。

ifstream打开文件是不创建文件,当文件不存在时,就会打开失败。

文件打开模式包括:in/out/app/ate/trunc/binary。

单独使用out模式时,会将原文件清空,使用out|app模式时,不会将源文件清空,且将在文件末尾添加数据,使用fstream(out|in)时,也不会清空源文件。

fstream(in|out)是将文件指针放置在文件首,如果想要将其放置在文件尾端需要增加ate命令。

写入读取二进制数据与文件的打开模式无关,至于写入读取函数有关。read write是二进制的读写函数。

struct Test
{

  int a;

  int b;

}

Test test={100,200},test2;

 ofstream fout;

fout.write(reinterpret_cast<char*>test,sizeof(test));

ofstream fin;

fin.read(reinterpret_cast<char*>test2,sizeof(test));

 由于string的sizeof大小是固定不变的,所以用上面的方式写入字符串是不正确的。应该用下面的方式,依次写入字符串。

Struct Test
{
    int a;
    string b;
}; 
Test test={2,"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},test2;
ofstream fout("Text1.txt",ios::out|ios::binary);
fout.write((char*)&test.a,sizeof(int));
fout.write(test.b.date(),test.b.length());
fout.close;
ifsteam fin("Text1.txt",ios::in|ios::binary);
fin.read((char*)&test2.a,sizeof(int));
fin.read(test2.b.date(),test.b.length());

 可以通过seekp(偏移量,位置枚举)(输出),seekg(输入)来定位,tellp,tellg来显示输入输出流指针在文件中的位置。streampos类是文件指针所处位置的值类型,实际上是一个long类型。

ios中有一个枚举类型,ios::beg代表文件起始位置,ios::cur代表文件目前位置,ios::end代表文件结束位置。

posted @ 2017-04-03 15:27  冥地魔王  阅读(306)  评论(0)    收藏  举报