std::fstream使用细节
1.文件不存不支持时打开文件模式不得有ios::in
• 如果文件不存在且打开时包括了ios::in模式则打开文件会失败。
fstream m_f;
m_f.open("d://123.csv", ios::in | ios::out | ios::binary);//文件不存在则会打开失败
• 我这边尝试行得通的做法是先判断文件是否存在
char* ch = "d://123.csv";
if (0 == _access(ch, 0))//文件存在
{
m_f.open(ch, ios::in | ios::out | ios::binary);//打开文件用于读写文件
}
else
{
m_f.open(ch, ios::out | ios::binary);//打开文件用于写文件
}
if (!m_f.good())
{
long err = errno;//获取系统错误码
}
2.“>>”与“<<”读写文件
• 调用<<
往文件写数据时并不会自动进行分割。
// 写数据到文件
m_f << int64_t(1000);
m_f << int64_t(2000);
// 从文件读数据
int64_t data = 0;
m_f >> data;//data的结果是10002000,也就是底层存的只是字符串,连续存两个数都连到一起了。
• 尝试了很多,存有换行分隔符的字符串数据使用<<
还挺方便的,读数据的话还是getline
吧。
// 写文件
string strMsg("有好的使用方法,欢迎来交流哈!");
m_f << strMsg;
// 读文件
string strLine;
while( getline(m_f, strLine) )
{
//处理strLine
}
3.读完之后写不进去了
iostate value (成员常量) | 标志 | 检查这些标记的函数 | ||||
---|---|---|---|---|---|---|
good() | eof() | fail() | bad() | rdstate() | ||
goodbit | 无错误 | true | false | false | false | goodbit |
eofbit | 输入操作时到达文件尾 | false | true | false | false | eofbit |
failbit | io操作发生逻辑错误 | false | false | true | false | failbit |
badbit | io操作发生读写错误 | false | false | true | true | badbit |
• 先读文件,从头读到尾,会使得eofbit
被置位,这时再往文件里面写数据是写不进去的,需要调用clear
清空标记位。
#include <iostream> // std::cout
#include <fstream> // std::fstream
int main () {
char buffer [80];
std::fstream myfile;
myfile.open ("test.txt",std::fstream::in|std::fstream::out);
// 读文件
string strLine;
while( getline(myfile, strLine) )
{
//处理strLine
}
//写数据到文件
myfile << "test"; //写不进去,因为上一步的读触发了end of file 即eof错误标记。需要读之后写一句“myfile.clear()”;
myfile.close();
return 0;
}