ofstream檔案輸出流把二進位制資料寫入檔案
阿新 • • 發佈:2019-01-27
1、新增標頭檔案
#include <fstream>
#include <sstream>
using namespace std;
2、執行檔案開啟寫入關閉操作
//在實際應用中,根據需要的不同,選擇不同的類來定義:如果想以輸入方式開啟,就用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();