Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++, fstream objects passed to functions as reference, const?

I know that generally, references to data should be isolated as a constant within a function so that the function can't change it, does the same hold true for fstream objects that are only being used for input?

Such as...

void doFoo(fstream &fileName)
{
  fileName.open("data.txt", ios::in);
} 

IF is it advisable, does it follow the same logic of most everything else?

Such as...

void doFoo(const fstream &fileName)
{
  fileName.open("data.txt", ios::in);
} 

also curious about output streams as well

I'm just wondering if it matters, and if so, why?

thanks!

like image 961
RebelPhoenix Avatar asked Feb 18 '23 19:02

RebelPhoenix


1 Answers

The constantness of a file does not translate to the constant attribute of the object used to access the file. Even for just reading a file, you must modify internal buffers, the current read position etc. The same applies to output, so basically a const stream is not useful.

BTW: If you want to make clear that a function only reads from a stream, pass it a std::istream&. Firstly, the "i" in istream makes reasonably sure that you don't write to it. Secondly, the missing "f" of fstream allows the use with stringstreams, too, or streams like cin.

like image 119
Ulrich Eckhardt Avatar answered Feb 20 '23 08:02

Ulrich Eckhardt