简体   繁体   中英

how do i legitimately change filename value of ofstream object?

I'm having troubles with ofstream , which is - when I change value of ofstream object like this

ofstream o_save; 

/*code*/

o_save = ofstream(filename);  //Problem is here

...the line above completely erase contents of file.

The question is how do I legitimately change filename value of ofstream object ?

PS I cant define it when I declare it, because I want it global and I'm not sure which save file I select.

The question is quite vague and contradictory, and the OP seems to have slept after asking the question. So I shall try to peek inside his head and try to elaborate what he wants.

For opening a file, there are many modes for that. Open it like this.

ofstream o_value ;
o_value.open("file.txt") ;

If you want to preserve the original contents of that file, use..

o_value.open("file.txt", ios::app) ;

If you want to close it later and open another one, close using...

o_value.close() ;

Chaning of file names is normally not allowed in case of ofstream . You can use rename from <cstdlib> . You can delete a file though using remove("file.txt") in <cstdio> .

What does it mean to "change the name" of an ofstream object? The only "name" an ofstream object has is the name of the variable. An ofstream object is a data stream. You can (on some systems) change the name of the file it is associated with, using rename , but somehow, I don't think this is what you want either. You can also close the stream, and reopen it on another file.

You cannot assign between iostream objects. If worse comes to worse, you can declare the global object as a pointer, and assign to it (using *o_save to write to it).

Finally, the standard says that when you open an ofstream , you truncate the file, if one exists. If this is not what you want to do, then you have to add some flags to the open mode. If you add std::ios_base::app , for example, you will no longer truncate the file, and all writes will be to the end of file (atomically, if the system supports it). Alternatively (albeit quite surprising), you could add std::ios::in to the flags; this will fail if the file doesn't exist, but will allow writing anywhere in the file. This is the only way to open a file for writing if you want to be able to write anywhere in the file, even if you don't want to read it.

The ofstream does not have some kind of an abstract name attribute, the name is just a parameter to some of its member functions, in that sense asking how to

change filename value of ofstream object

is meaningless.

In general you can rename files with std::rename from <cstdlib> or use Boost.Filesystem.

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