????//文件打開方式選項:
????// 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;
}