简体   繁体   中英

Switch files in variables (cpp)

my Problem is best explained in code:

fstream One;
fstream Two;
fstream Three;
One.open(path1, ios_base::out);
Two.open(path2, ios_base::out);
Three.open(path3, ios_base::out);

As you can see above i have three fstream variables and I've loaded three seperate files into them. Now I want to Change some files.

One=Three;
Three=Two;

So that when i use One file, i will be using file from path3. I know that i probably can't assign fstreams like that. And here's my question: how can i do that? Sorry for my english, if something is not clear then simply comment. Thanks in advance!

#include <algorithm>
#include <fstream>
using namespace std;

auto main() -> int
{
    auto path1 = "a.txt";
    auto path2 = "b.txt";
    auto path3 = "c.txt";

    ofstream one;
    ofstream two;
    ofstream three;
    one.open(path1);
    two.open(path2);
    three.open(path3);

    swap( one, two );
    two << "Two" << endl;
}

Things to note:

  • Use ofstream for pure output streams.
  • Don't use global variables.
  • Ideally check for failures (not done in the above code).

You could use pointers to refer to different fstream objects. I would suggest you to stay with stack allocation:

fstream One;
fstream Two;
fstream Three;
One.open(path1, ios_base::out);
Two.open(path2, ios_base::out);
Three.open(path3, ios_base::out);

And then you can use pointers like this:

fstream* A = &One;
fstream* B = &Two;
/*...*/
A = &Three;

I think this answers your question, but I think what you are really looking for is a way to use the same function with different fstream s. To do this, simply pass them as reference parameters:

void foo(fstream& fs){/*...*/}

And then call it with whatever fstream you like:

foo(A);
foo(B);

PS: and even if the fstream s are global variables (I would strongly suggest to change this) you can still pass them as parameters to functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM