我在处理 C++ 中的随机访问文件类时遇到问题,它应该允许从文件中写入和读取任何原始数据类型。但是,即使代码编译并执行,也不会向文件写入任何内容。
文件在构造函数中打开:
RandomAccessFile::RandomAccessFile(const string& fileName) : m_fileName(fileName) {
// try to open file for reading and writing
m_file.open(fileName.c_str(), ios::in|ios::out|ios::binary);
if (!m_file) {
// file doesn't exist
m_file.clear();
// create new file
m_file.open(fileName.c_str(), ios::out | ios::binary);
m_file.close();
// try to open file for reading and writing
m_file.open(fileName.c_str(), ios::in|ios::out|ios::binary);
if (!m_file) {
m_file.setf(ios::failbit);
}
}
}
测试 main 中的函数调用:
RandomAccessFile raf("C:\Temp\Vec.txt");
char c = 'c';
raf.write(c);
写函数:
template<class T>
void RandomAccessFile::write(const T& data, streampos pos) {
if (m_file.fail()) {
throw new IOException("Could not open file");
}
if (pos > 0) {
m_file.seekp(pos);
}
else {
m_file.seekp(0);
}
streamsize dataTypeSize = sizeof(T);
char *buffer = new char[dataTypeSize];
for (int i = 0; i < dataTypeSize; i++) {
buffer[dataTypeSize - 1 - i] = (data >> (i * 8));
}
m_file.write(buffer, dataTypeSize);
delete[] buffer;
}
如果我调试它,我可以清楚地看到“c”在写入文件时在缓冲区中。有什么建议么?
谢谢菲尔