I’m having a problem working on a Random Access File class in c++, which should allow to write & read any primitive datatype from a file. However, even though the code compiles and executes, nothing is written to the file.
File is openend in constructor:
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);
}
}
}
Test call of function in main:
RandomAccessFile raf("C:\Temp\Vec.txt");
char c = 'c';
raf.write(c);
Write function:
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;
}
If I debug it I can cleary see that ‘c’ is in the buffer when it’s written to the file.
Any suggestions?
Thanks
Phil
Solved it myself with a little luck.
Apparently, fstream.open doesn’t work with absolute paths.
Replacing “C.\temp\vec.txt” with just “temp” solved it.