Illia Levandovskyi
Illia Levandovskyi

Reputation: 1318

ifstream --> ofstream c++

I have a function that gets ifstream variable, but I have to write into this file in some situations. E.g.

main()
{
  ifstream dataFile("filename.txt");
  foo(dataFile);
}

void foo(ifstream &df)
{
  if(df.good()) {...}
  else {
     //here I need to write str into the "filename.txt"
     //but I don't know how to do it properly!
  }
}

As I can imagine, the simplest way is to get somehow name of the file from df in foo()... But how?

imagine: I CAN'T use fstream. For some reason I have only ifstream& and don't know name of the file. E.g. I get ifstream& from some closed library function.

Upvotes: 0

Views: 6045

Answers (2)

Mark B
Mark B

Reputation: 96241

Unfortunately given your restrictions that you have only an ifstream and no filename, there is no portable way to write back into that file.

There may be non-portable ways to solve this problem. For example some unix implementations may provide an fd function on the filebuf object you can obtain from rdbuf in the ifstream. Windows may or may not provide a similar capability.

I'll close by noting that it sounds like you may be solving the wrong problem here, and you should at least take a moment to visit your design (and why you need to write to a file whose name you do not know).

Upvotes: 0

The Quantum Physicist
The Quantum Physicist

Reputation: 26276

Use fstream rather than ifstream:

fstream dataFile("filename.txt",ios::in | ios::out | ios::app);

With this you can read and write to the file.

And OF COURSE, pass your fstream object by reference, not by value. fstream is non-copyable.

Upvotes: 4

Related Questions