
新手练习 C++文件操作。我现在已经可以写入了,但是不会读取,原因是写入的时候以写入的方式打开了文件,但是读取的时候就纠结到了是不是需要将文件关闭一次在以读取的方式打开
class CFileOper { fstream m_pstrFile; public : CFileOper(const char *cFileDir) { try { m_pstrFile.open(cFileDir, ios::out | ios::binary); if (!m_pstrFile.is_oen()) { throw "文件打开失败"; } } catch (const char * ErrorInfo) { cout << ErrorInfo; } } void writeDataToFile(char *cData, const int &nDataCount) { for (int i = 0; i < nDataCount; i++) { // 每遇到 endl 引发一次同步,这种方式是不是会增加 IO ?还是使用手动吧 // m_pstrFile << cData[i] << endl; m_pstrFile << cData[i] << "\n"; } // 手动引发同步 m_pstrFile.sync(); } void printFile(const char *cFileDir) { /* 主要的困惑就是这里,是不是需要关闭一次文件,然后再以读的方式打开?*/ if (!m_pstrFile.is_open()) { cout << "Error opening file"; exit(1); } if (!m_pstrFile.tellg()) { m_pstrFile.seekg(0, ios::beg); } char content[200] = { 0 }; int i = 1; while (!m_pstrFile.eof()) { m_pstrFile.getline(content, 100); cout << i << " :" << content << endl; i++; } } virtual ~CFileOper() { m_pstrFile.close(); } }; 1 mashiro233 2018-05-22 20:39:13 +08:00 是的。如果你要进行读写操作,那么在构造函数打开文件那里就应该设置成可写可读权限。 |
2 Number13 OP @mashiro233 m_pstrFile.open(cFileDir, ios::out | ios::in | ios::binary); 是这个样子么??我这样试过然并卵啊 |
3 mashiro233 2018-05-22 22:28:49 +08:00 @Number13 具体错误是体现在哪里呢? |
4 wevsty 2018-05-22 22:34:10 +08:00 |
5 Number13 OP @wevsty @mashiro233 m_pstrFile.open(cFileDir, ios::binary | ios::out | ios::in); 我在构造函数中将文件的打开方式改成了这个样子,但是在读的函数里,while 循环那块并不能将内容输出,而且它被判断为了指针在结束的位置 |
6 mashiro233 2018-05-23 16:19:52 +08:00 |
7 Number13 OP @mashiro233 嗯,经过验证你的是正确的,不过,m_pstrFile.tellg() 不能直接进行比较,因为我看了一下原型,tellg()貌似并不是直接返回一个 int,而是一个需要类型模板,所以我 int tellg = m_pstrFile.tellg(); if (tellg != 0){} 用了这样的方式去做的比较,我试了一下,将 (int)m_pstrFile.tellg() 强转后也是可以的。 |
8 wutiantong 2018-05-28 14:18:20 +08:00 既然你“新手练习 C++文件操作”,那你写文件就用 ofstream 写个函数,读文件就用 ifstream 写个函数 你这个 class 写得实在是太尬了 |