您的位置:首页 > 移动开发 > IOS开发

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

2010-05-31 17:26 751 查看
把网上搜索的内容大致汇总一下:

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios path 扩展 string