C++文件IO

来源:互联网 发布:in照片软件 编辑:程序博客网 时间:2024/06/06 09:52


经过两三天的学习 对C++ IO总结如下:

   总的继承关系: 

 

iostream包含8个流对象 cin cout cerr clog wcin wcout wcerr wlog 

以上标准输入输出 主要 >>抽取运算符 <<插入运算符  get write可以完成。


而现实开发 主要是对文件的处理:

ifstream ofstrem 他们也是从标准输入输出而来的:


文件模式:

ios_base::in  ios_base::out  ios_base::ate  ios_base::app(不删除文件,直接添加到最后) ios_base::trunc(如果文件存在则删除文件) ios_base::binary(二进制方式读写文件)  


文件分类两种:文本文件(又叫ASCII文件)和二进制文件 看下下面这个例子:



说明字符 在二进制或者文本文件下是没有区别的 但是数字很大 因为一个一个字符占一个字节。

一般来说 二进制文件小 但是移植性差。

使用二进制存储:

struct Stu{

 char a[10];

  int   n;

}stu;

 ofstream fout("c:\text.dat",std::ios_base::binary);

 fout.write((char*)&stu,sizeof stu);

必须使用std::ios_base::binary模式 必须使用write函数

读二进制文件则:

ifstream fin("c:\text.dat",std::ios_base::binary);

 fin.read((char*)&stu,sizeof stu);


随机存取:

seekg(strea魔法粉,ios_base:;dir)将输入指针移动到指定位置 第一个参数到第二个参数的位置

ios_base::end ios_base::beg ios_base::cur三种

例子:fin.seekg(0,ios_base::end)文件末尾

seekp()将输出指针移动到指定位置

检查文件指针当前的位置:

输入流tellg() 输出流tellp()




    //读取文本文件
    ifstream fin("C:\\Users\\pan\\Desktop\\pppppp.txt");
    if(fin.is_open()) //判断是否打开文件
    {

      fin.seekg(0,ios::end);//移动指针到文件尾
      long long count=fin.tellg();
     cout<<count<<endl;//文件长度
     fin.seekg(0, ::std::ios::beg);//移动指针到文件
        while(!fin.eof()) //判断是否文件是否结束
        {
            char c;
            fin.get(c);
            cout<<c;
        }
        fin.close();//关闭文件
    }

 
读取二进制文件
struct Stu
{
    char a[10];
    int n;
    char b[10];
};


int main()
{


     struct Stu s= {"ccc",1000,"mmm"};
     ofstream out("C:\\Users\\pan\\Desktop\\pppppp.dat",ios_base::binary);
     out.write((char*)&s,sizeof s);
     out.close();


     struct Stu s2;
     ifstream in("C:\\Users\\pan\\Desktop\\pppppp.dat",ios_base::binary);
     while(in.read((char*)&s2,sizeof s2)){
        cout<<s2.n;
     }
    in.close();

}

ifstream read到文件尾,返回0值,其它时候返回非0值










0 0
原创粉丝点击