1) In general, you don't know or care. The ofstream object takes care of flushing the buffer when necessary.
2) You write to the stream. Again, you don't know or care when the buffer is flushed since it is done automatically when needed.
3) Won't happen as it gets flushed when full.
4) The buffer is generally implemented as a circular buffer. See my explanation below for an example of what happens when the buffer is flushed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Writing a binary file
#include <iostream>
#include <fstream>
usingnamespace std;
int main ()
{ constint size = 1000;
char memblock[size];
ofstream file ("example.bin", ios::binary|ios::ate);
if (! file.is_open())
{ cout << "Unable to open file" << endl;
return 1;
}
memset (memblock, 'A', size);
file.write (memblock, size);
file.close();
return 0;
}
In the above example, let's assume ofstream's buffer size is 512 bytes. The write at line 16 will physically write 512 bytes to the disc and leave 488 bytes in the buffer. When the file is closed, the remaining 488 bytes will be written to the disc. The size of the buffer is implementation dependent and may be something other than 512 bytes I used in this example. The actual size of the buffer makes no difference to your program.
You didn't show tempwriter.h, so I can only guess at your class declaration.
tempwriter.cpp line 29: you have no protection of line.length() exceeding the size of memblock.
I also don't think you want to use memset here. memset sets all characters of the buffer to the second argument. Did you intend memcpy?
Why not eliminate line 29 and just use this at line 30:
Everywhere I read they mention the need for read/write buffers. Is that wrong? Or does the line.c_str() in
tempFile.write (line.c_str(), line.length());
creates a buffer in the background?
I fell that this approach is much safer as I don't have to worry about buffer overflow.
From the c_str() reference
This array includes the same sequence of characters that make up the value of the string object plus an additional terminating null-character ('\0') at the end.
Does that mean that the null-character ('\0') is written to disk?
> Does that mean that the null-character ('\0') is written to disk?
Very often, no. If you specify the length that includes the null character as well, yes it will work : tempFile.write (line.c_str(), line.length() + 1);