默认文件输入/输出模式
#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())
{
//...
}