ios::binary和ios::text打开文件区别,fstream读写文件示例

把网上搜索的内容大致汇总一下:

1.text方式写入文件会将换行(/n)扩展成/r/n, 读文件时则自动转换回来

2.binary方式则不会作任何扩展,与读写内容一致

3.默认为text方式

 

详细参考:http://blog.csdn.net/wanfustudio/archive/2007/09/14/1785131.aspx

 

附录:自己写的使用fstream读写文件的两个函数

#include <fstream>

using namespace std;

 

bool Preprocess::ReadParseRsltFile(tstring FileName)

{

    TCHAR szFull[MAX_PATH] = {0};

    _tcscpy_s(szFull, MAX_PATH, m_szDataFileDir);

    _tcscat(szFull, TEXT("//"));

    _tcscat(szFull, FileName.c_str());

    _tcscat(szFull, TEXT("_r"));

 

    wifstream fin;

    fin.open(szFull, ios::binary);

    if (fin.bad())

    {

        return false;

    }

    fin.imbue(std::locale("chs"));

 

    TCHAR szSize[16] = {0};

    fin.getline(szSize,16);  //第一行为文件大小

    int nSize = _ttoi(szSize);

 

    tstring strTmp;

    for(int i=0; i<nSize; i++)

    {

        getline(fin, strTmp);

        m_vSenParRslt.push_back(strTmp);

    }

    fin.close();

 

    return true;

}

void Preprocess::WriteFiles(tstring FileName, const vector<tstring>&vContent)

{

    TCHAR szFull[MAX_PATH] = {0};

    _tcscpy_s(szFull, MAX_PATH, m_szDataFileDir);

    _tcscat(szFull, TEXT("//"));

    _tcscat(szFull, FileName.c_str());

 

    wofstream fout;

    fout.open(szFull, ios::binary|ios_base::trunc);

  //  fout.clear();

    fout.imbue(std::locale("chs"));

    fout<<vContent.size()<<"/n";

    for(int i=0; i<vContent.size(); i++)

    {

        fout<<vContent[i].c_str()<<"/n";

    }

    fout.close();

}

写入的内容包含中文,所以必须加上: fout.imbue(std::locale("chs"));

tstring 是自己定义的宏,代表string 或者wstring

#ifdef _UNICODE

#define tstring wstring

#else

#define tstring string

#endif

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值