-
ostream
"ofstream::<<" looks much easier to use then "ofstream::write".
Any concerns that we should rather use "ofstream::write"?
Maybe buffer overflows and such?
Code:
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
ofstream file("test.txt" );
int main()
{
string f,i;
f = "Hello\n";
i = " world\n";
file.write("Hello", 5);
file.write(i.c_str(),7);
file << "Hello" << i;
return 0;
}
PS There is a typo in the title meant to be ofstream, Sorry.
-
You should use write when you want to write the bytes of something, rather than the representation that operator<< is coded for.
E.g
Code:
#include <iostream>
int main()
{
int i = 4407873;
std::cout.write(reinterpret_cast<char*>(&i), sizeof(i));
}
This might print "ABC", except it isn't very portable due to endianness or what-not.
Or more generally, it can be used to output byte arrays that do not represent C-style null-terminated strings and may therefore contain embedded '\0'-s. Note that it has a second parameters specifying the size of the char array. operator<< outputs only up to the first null-character it encounters.
-
Thank you Anon!
So if i understand well "ofstream::write" should be used when writing a binary file.
-
I suppose so. Binary file IO doesn't translate '\n' into platform-specific end-of-line sequence which would corrupt data where '\n' does not have that meaning (when you output the bytes of an integer, it might well contain bytes with the value of '\n').