C++文件读写(一):fstream

默认文件输入/输出模式

#include <fstream> 
fstream,ifstream,ofstream 构造函数中默认的输入/输出模式如下:
/*
explicit ofstream(const char* filename, ios_base::openmode mode = ios_base::out);
explicit ifstream(const char* filename, ios_base::openmode mode = ios_base::in );
explicit fstream (const char* filename, ios_base::openmode mode = ios_base::in | ios_base::out);
*/

txt文件换行异常问题处理

//写入txt文件时换行用记事本打开可能会有问题的一种解决方式。待完善细节...
#include "stdafx.h"
#include <vector>
#include <string>
#include <fstream>
using namespace std;

int main()
{
    vector<string> vstr;
    vstr.push_back("画画");    vstr.push_back("喝茶");
    vstr.push_back("问号");    vstr.push_back("什么");

    char chPath[256] = { 0 };
    sprintf(chPath, ("D:\\select.txt"));
    //输出文件测试
    ofstream ofs(chPath, ios::out | ios::trunc);
    if (ofs.is_open())
    {
        for (auto it = vstr.begin(); it != vstr.end(); it++)
        {
            ofs << it->c_str() << endl;
        }
        ofs.close();
    }

    //写入文件测试
    vector<string> vSelect;
    ifstream ifs(chPath, ios::in | ios::binary);
    if (ifs.is_open())
    {
        string strLine = "";
        while (std::getline(ifs, strLine))
        {
            int pos = strLine.size() - 1;
            if (strLine[pos] == 0x0d)
                strLine.erase(pos, 1);
            vSelect.push_back(strLine);
        }
        ifs.close();
    }
    return 0;
}

坑爹的知识点备忘:

上面用了strLine.erase(pos, 1); 我第一次写的其实是strLine[pos]='\0'; 
这他妈的有错吗!是的!错了!  
下面的代码查找不到!不信你自己试试!
原因是设置最后的字符为'\0'后string的size并不会改变。不会改变。。不会改变。。。
//或者写 strLine.erase(strLine.end()-1); 删最后一个字符

str[str.size() - 1] = '\0' 用了之后 str.length() 和 strlen(str.c_str()) 就不相等了。
上面的语义只是把最后一个字符设置为'\0',str的长度并没有减少。string内部不会区分字符的值。

auto it = find( vSelect.begin(), vSelect.end(), "画画");
if (it != vSelect.end())
{
    //...
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值