Why, when I use following code snippet the result is zero regardless of the file size, but when I remove ios::binary in open() it does what it's supposed to do?
fstream f1;
streampos begin, end;
f1.open("file1", ios::binary);
f1.seekg(0, ios::beg);
begin = f1.tellg();
f1.seekg(0, ios::end);
end = f1.tellg();
f1.close();
cout << end - begin << endl;
I assume that by "when I remove ios::binary" you mean you remove the entire argument:
f1.open("file1");
The function open() has two parameters - file name and mode. The mode one has a default argument of std::ios_base::in | std::ios_base::out. So if you don't specify anything, this deault gets used.
If you specify ios::binary, however, you replace the default argument. And since you have specified neither in nor out, the open() call fails. Putting an if() around the open() would tell you — remember you should always check for error with I/O.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With