GaoYanFei

导航

 
    #include <fstream>  
    #include <sstream>  
      
    using namespace std;  
    //在实际应用中,根据需要的不同,选择不同的类来定义:如果想以输入方式打开,就用ifstream来定义;如果想以输出方式打开,  
    //就用ofstream来定义;如果想以输入/输出方式来打开,就用fstream来定  
      
    //ofstream         //文件写操作 内存写入存储设备     
    //ifstream         //文件读操作,存储设备读区到内存中    
    //fstream          //读写操作,对打开的文件可进行读写操作  
      
    //(一)打开文件的方式在ios类(所以流式I/O的基类)中定义,有如下几种方式:  
    //ios::in   为输入(读)而打开文件  
    //ios::out  为输出(写)而打开文件  
    //ios::ate  初始位置:文件尾  
    //ios::app  所有输出附加在文件末尾  
    //ios::trunc    如果文件已存在则先删除该文件  
    //ios::binary   二进制方式 这些方式是能够进行组合使用的,以“或”运算(“|”)的方式:例如  
      
    //(二)、保护模式  
    //#define _SH_DENYRW      0x10    /* deny read/write mode */拒绝对文件进行读写   
    //#define _SH_DENYWR      0x20    /* deny write mode */拒绝写入文件   
    //#define _SH_DENYRD      0x30    /* deny read mode */拒绝文件的读取权限   
    //#define _SH_DENYNO      0x40    /* deny none mode */读取和写入许可   
    //#define _SH_SECURE      0x80    /* secure mode */共享读取,独占写入   
    //注意:假设A进程以_SH_DENYRW 打开,那么是B进程不能再对文件进行读写。  
      
    ofstream ofs;                           //打开文件用于写,若文件不存在就创建它  
      
    locale loc = locale::global(locale(""));               //要打开的文件路径含中文,设置全局locale为本地环境   
      
    ofs.open("./out.bin",ios::out| ios::app | ios::binary,_SH_DENYNO); //输出到文件 ,追加的方式,二进制。 可同时用其他的工具打开此文件  
      
    locale::global(loc);                          //恢复全局locale  
      
    if (!ofs.is_open())return;  //打开文件失败则结束运行    
      
    for (int i=0;i<100;i++)  
    {  
        char* buffer = "fdsfdsfdsfdsfdsfds\n";  
        ofs.write(buffer, sizeof(char)*17);   
        ofs.flush();  
        Sleep(1000);  
    }  
      
    ofs.close();    
ofstream  file;  
locale::global(locale(""));//将全局区域设为操作系统默认区域  
string strFileName = "e:\\abc.bin";  
file.open(strFileName.c_str());  
locale::global(locale("C"));// 还原全局区域设定   
  
std::ostringstream   str("");  
str <<    "123" << "\n";  
file.write(str.str().c_str(),str.str().length());  
file.close(); 

 

posted on 2017-11-21 18:00  YanFeiGao  阅读(945)  评论(0)    收藏  举报