zoukankan      html  css  js  c++  java
  • fstream

    fstream file("b.txt", ios::in|ios::out|ios::app);

    mode

    • ate - seek to the end of stream immediately after open,你处于文件末尾,但你可以在文件的任何地方写数据。不会导致create属性
    • app - seek to the end of stream before each write,附加到已有文件末尾, 可造成out属性
    • in 表示只读属性
    • out 表可写属性+create属性
    • in+out 表只读+可写属性(没有create属性)
    • trunc
    • ios::nocreate——如果文件不存在,则打开操作失败。
    • ios::nocreplace——如果文件已经存在,则打开操作失败。
    class	              default mode to parameter
    ofstream	        ios::out | ios::trunc
    ifstream	        ios::in
    fstream	                ios::in | ios::out
    
    //fstream file("b1.txt", fstream::in|fstream::out); do NOT create if no exist
    fstream file("b1.txt", fstream::out);   // create
    file<<"s";
    cout<<"s";
    file.close();
    }
    

    文件读写的步骤:

    1、包含的头文件:#include
    2、创建流
    3、打开文件(文件和流关联)
    4、读写 (写操作:<<,put( ), write( ) 读操作: >> , get( ),getline( ), read( ))
    5、关闭文件:把缓冲区数据完整地写入文件, 添加文件结束标志, 切断流对象和外部文件的连接

    https://blog.csdn.net/sheng_bw/article/details/85336298

      if (OpenFile.fail())  
        {  
            cout<<"打开文件错误!"<<endl;  
            exit(0);  
        }
    
    istream& read(char *buffer,int len);  
    ostream& write(const char * buffer,int len);  
    
        if (!in.is_open()){
            std::cout<<"Error opening file"; exit(1);
        }
    
        while (!in.eof()){
            in.getline(buffer,100);
            std::cout<< buffer << std::endl;
        }
    

    说明:

    1、程序不再使用文件时,为什么要关闭文件?
    因为:1)文件缓冲区是一块小的内存空间.
    2)操作系统限制同时打开的文件数量
    注意:close ( ) 函数关闭文件,但流对象仍然存在。

    2、文件的默认打开方式为文本文件,要是想以二进制的方式处理,在打开时要用 ios::binary 显式声明。

    3、针对文本文件操作时,get函数和>>的区别:
    区别:在读取数据时,get函数包括空白字符(遇空白字符不停止读取)
    >>在默认情况下拒绝接受空白字符(遇到空白符停止读取)

  • 相关阅读:
    Andriod调试桥
    抓包工具charles的使用
    测试常用工具
    Indentation error codes
    Cmder 中文乱码的解决方法
    修改Cmder命令提示符
    统计单词出现的字数
    将字串内容输出到文件
    python数据实例str
    python语法检查工具
  • 原文地址:https://www.cnblogs.com/friedCoder/p/12467736.html
Copyright © 2011-2022 走看看