C++文件文件及二進制文件讀寫

????//文件打開方式選項:

????// ios::in    = 0x01, //供讀,文件不存在則創(chuàng)建(ifstream默認(rèn)的打開方式)

????// ios::out    = 0x02, //供寫,文件不存在則創(chuàng)建,若文件已存在則清空原內(nèi)容(ofstream默認(rèn)的打開方式)

????// ios::ate    = 0x04, //文件打開時,指針在文件最后??筛淖冎羔樀奈恢茫:蚷n、out聯(lián)合使用

????// ios::app    = 0x08, //供寫,文件不存在則創(chuàng)建,若文件已存在則在原文件內(nèi)容后寫入新的內(nèi)容,指針位置總在最后

????// ios::trunc   = 0x10, //在讀寫前先將文件長度截斷為0(默認(rèn))

????// ios::nocreate = 0x20, //文件不存在時產(chǎn)生錯誤,常和in或app聯(lián)合使用

????// ios::noreplace = 0x40, //文件存在時產(chǎn)生錯誤,常和out聯(lián)合使用

????// ios::binary  = 0x80  //二進制格式文件

/* file read && write */

#include <fstream>

#include <iostream>

#include <cstring>

#include <sstream>

using namespace std;

/* write to file */

int txt_write(const char* fname, string data)

{

/* ios:app 文件不存在則創(chuàng)建, 在末尾寫入 */

fstream f(fname, ios::out | ios::app);

if (f.bad()) {

return -1;

}

f << data;

f.close();

return 0;

}

/* read file all */

int txt_read(const char *fname, string &data)

{

std::stringstream buffer;?

fstream f(fname, ios::in);

if (f.bad()) {

return -1;

}

buffer << f.rdbuf();

data = buffer.str();

f.close();

return 0;

}

int write_bin(const char *fname, char *data, int dlen)

{

fstream f(fname, ios::out | ios::binary | ios::app);

if (f.bad()) {

return -1;

}

f.write(data, dlen);

f.close();

return 0;

}

int read_bin(const char *fname, char *data, int dlen)

{

fstream f(fname, ios::in | ios::binary);

if (f.bad()) {

return -1;

}

f.read(data, dlen);

f.close();

return 0;

}

int main()

{

/* write file */

string wdata = "hello world11!\n";

txt_write("txt_write.txt", wdata);

/* read file */

string rdata;

txt_read("txt_write.txt", rdata);

cout << "rdata:" << rdata << endl;

/* write bin file */

string wbdata = "hello world11!\n";

txt_write("bin_write.bin", wbdata);

/* read file */

string rbdata;

txt_read("bin_write.bin", rbdata);

cout << "rbdata:" << rbdata << endl;

return 0;

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容