1.回车
STL里有个fstream类,用来读写文件,对于文本文件的回车处理得注意个问题,那就是开方模式中要使用ios_base::binary,才能正确的进行读写。读出数据时要有启用这个模式,写的时候也一样。
- const char* filename="a.txt";
- fstream file;
- file.open(filename, ios_base::in | ios_base::binary);
- if (file.fail()) goto LB_FAIL;//失败
- //do something with file
- file.flush();
- file.close();
- //-----------------------------------
- file.clear(); //清除对象中保留的状态
- file.open(filename, ios_base::out | ios_base::binary);
- //do something with file
- file.flush();
- file.close();
- file.clear;
- LB_FAIL: return FALSE;
2.长度
文件长度可用来获取。目前没有办法缩短文件,如果改写后数据长度比原来的小,那么用ios_base::trunc清空内容再重新写入新数据。注:超笨!!!
- #include <fstream>
- const char* filename="a.txt";
- fstream file;
- file.open("a.txt", ios_base::in | ios_base::binary);
- file.seekg(0, fstream::end);
- cout << "file size: " << file.tellg() << std::endl;