-
file i/o and classes
i have a program that it a little wacked (cause i suck at programming)...anyway, i need some clarification on input and output to/from a file.
if you declare:
//code
fstream myfile;
myfile=open("myfile.txt", ios::in);
//endcode
i understand that this will open "myfile.txt", but does it create that file if it doesn't already exist?
*sigh*...tonight ends the night of the endless summer.
-
also...
the thing that's kind of messing me up is that i have file being opened and read by the constructor in one class, and then being written to by the deconstructor in that same class...so i dont think that the deconstructor is being called...it could also be that i just dont understand deconstructors.
-
I'm pretty sure that it will not create one. I think because you are looking to get input FROM the file that it will return an invalid handle if it doesn't exist. Here are some other things to consider when dealing with files. If you just want to get input from a file you can do this.
ifstream fin( "data.txt" );
or for output
ofstream fout( "data.txt" );
When you specify fstream you are saying that you may do input AND output.
Also, if you do not wish that the file be created when attempting to output to a file, you can specify ios::nocreate and if the file doesn't exist it will not be created.
-
hmm
so, i actually want to be using a fstream...like this:
//code
fstream myfile;
myfile=open("myfile.txt");
//
will this create the file if that file is not found?
-
>i understand that this will open "myfile.txt", but does it create that file if it doesn't already exist?
No. To create it if it doesn't exist use either:
Code:
myfile.open("myfile.txt", ios::in | ios::out);
Or:
myfile.open("myfile.txt", ios::in);
if (!myfile.is_open())
myfile.open("myfile.txt", ios::out);
And there's also:
myfile.open("myfile.txt", ios::app);
to append to a file