读书笔记--C++文件操作

来源:互联网 发布:中国移动l2tp拨号软件 编辑:程序博客网 时间:2024/05/21 22:47

  在C++中,对文件的操作是通过stream的子类fstream(file stream)来实现的,在头文件<fstream>中定义
  一、打开文件
  fstream类的成员函数open(),原形:void open(const char *filename,int mode,int access)
filename:打开的文件名字            mode:打开文件的方式              access:打开文件的属性

  打开文件的模式:
in 打开文件做读操作      out 写操作,文件会清空      app 在文件尾追加    ate 定位在文件尾
trunc 如果文件存在,把文件尾长度设为0(清空已存在的文件流) 
nocreate 文件不存在时打开失败              noreplace 打开文件如果存在则失败
binary 以二进制模式进行IO操作

  打开文件的属性:
0:普通文件,打开访问                 1:只读文件
2:隐藏文件                           4:系统文件
可以用“或(|)”或者“+”把以上属性连接起来
如果open函数只有文件名---一个参数,则以读/写普通文件打开
例:file1.open("c://config.sys");<======>file1.open("c://config.sys",in|out,0);


   二、关闭文件
   fstream提供成员函数close()来操作
  
  
   三、读写操作
   1、file2<< "I love you";   //向文件写入字符串“I love you”
      int i;
      file2>>i;               //从文件读出一个整数值i
   2、二进制文件的读写
      (1) put()
          put()函数向流写入一个字符。原形为ofstream &put(char ch);
          file1.put('c');就是向流写一个字符'c'
      (2) get()
          get()函数有三种重载形式:
            第一种:ifstream &get(char &ch):从流中读取一个字符,结果保存在引用ch中。如果到文件            尾则返回空字符
            第二种:file2.get(x);表示从文件中读取一个字符,保存在x中。达到文件尾则返回EOF
            第三种:ifstream &get(char *buf,int num,char delim='/n'); 把字符读入由buf指向的数            组,直到读入num个字符或遇到由delim指定的字符。如果没有delim这个参数,就使用默认置            换行符'/n'
           
           
    四、文件定位
    C++的文件定位分为读位置和写位置的定位
    seekg()设置读位置             seekp()设置写位置
    istream &seekg(streamoff offset,seek_dir origin);
    ostream &seekp(streamoff offset,seek_dir origin);
    offset 偏移量            seek_dir 移动的基准位置
    seek_dir是值为枚举类型:beg 文件开头;cur 当前位置;end 结尾
    以上两个函数一般用于二进制文件
    file1.seekg(1234,cur);      //把文件的读指针从当前位置后移1234个字节
   
   
   
    ifstream input;
    vector<string>::const_iterator iter=files.begin();
    while( iter!=files.end() )
    {
  if( !input )
  {
   break;
  }
  while( input>>s )
  {
   process(s);
  }
  input.close();
  input.clear();          //打开已存在的流对象,必须在每次偏移循环时关闭和清空
  ++iter;
    }          
    
    
    每个IO类定义了三个iostate类型的常量值,分别表示特定的位模式:
    badbit标志着系统级的故障,如无法恢复的读写错误
    failbit标志着希望获得数值型数据而输入了字符,这种导致设置failbit的问题通常可以修正
    eofbit标志着遇到文件结束符,此时同时还设置了failbit
   
    流的状态由bad、fail、eof和good操作揭示。clear和setstate操作用于改变条件成员状态
int ival;
//read cin and test only for EOF;loopis executed even if there are other IO failures
while( cin>>ival,cin.eof() )   //先读取,然后返回是否到达文件结束
{
 if( cin.bad() )
 {
  throw runtime_error("IO stream corrupted");
 }
 if( cin.fail() )
 {
  cerr<< "bad data,try again";
  cin.clear(istream::failbit);      //reset the stream
  continue;
 }
}
      
    输入缓冲区的刷新:
    cout<< "hi"<<flush;                     //flush the buffer;adds no data
    cout<< "hi"<<ends;                      //insert a null,then flushes the buffer
    cout<< "hi"<<endl;                      //insert a newline,then flushes the buffer
    cout<< unitbuf<< "fisrt"<< "second"<< nounitbuf;//每次执行完写操作符后都刷新流      
               

原创粉丝点击