Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this code always return file size zero?

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;
like image 526
Mojee KD Avatar asked Apr 23 '26 07:04

Mojee KD


1 Answers

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.

like image 176
Angew is no longer proud of SO Avatar answered Apr 24 '26 20:04

Angew is no longer proud of SO