Reputation: 99
I have a code written in c++ in visual studio, which basically writes a set of floating point numbers ( 70 floating points )to a binary file on each tick of a timer.The numbers are acquired from a machine which an experiment is done.
WriteToFile( float* buffer, int buffersize )
{
ofstream out;
out.open( filename,ios::app)
for(int i =0;i< buffersize ;i++) // buffersize is 70 here
{
out.precision(6);
out.setf(ios::fixed,ios::floatfield);
out.write( (const char*) &buffer[i], sizeof(float));
}
}
This function is called for each tick of a timer.This is taking so much of time, even after the experiment is done i have to wait the program to acquire the data and save it to the file.The reason for its slowing down is, for every tick it need to open the binary file and have to find the location where it previously stopped.If there is a way i can keep the file open all the time and the place location pointer in the same location where it stopped previously i might be able to speed it up.Does any body have any suggestions on it ? Basically how to keep and ofstream open, even after the function exits ?
Upvotes: 1
Views: 1898
Reputation: 171127
The C++ way would be to encapsulate the timer function and the stream object into a class, something like this:
class BufferWriter
{
std::ofstream out;
public:
explicit BufferWriter(const std::string& filename)
: out(filename.c_str(), std::ios::app)
{
out.precision(6);
out.setf(std::ios::fixed, std::ios::floatfield);
}
void writeToFile(float *buffer, std::size_t bufferSize)
{
for (size_t i = 0; i < bufferSize; ++i) {
out.write((const char*)(buffer + i), sizeof(float));
}
}
};
Simply create an instance of this somewhere, and call its writeToFile()
function in each timer tick. When the instance is destroyed, the file will be closed. You can also flush()
it at the end of each writeToFile()
if you want.
To elaborate on the use case, you could do it for example like this:
int main()
{
BufferWriter buf("MyBufferFile.dat");
Timer t = createTimer();
t.setTickCallback(buf, &BufferWriter::writeToFile); // call buf.writeToFile() on each tick
t.start();
waitUntilFinished(t);
}
The important point is for the BufferWriter
instance to exist as long as the entire timer-using operation runs. As long as the BufferWriter
instance exists, its out
member will exist as well and the corresponding file will remain open.
Upvotes: 3