Hi everyone I'm new here, I'm using English but not so good. Hopefully I can share my few experience with all of you.
For the first post, I wanna ask about using file in c++ as an input output process.
Below is several code that I wrote recently:
1.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include <fstream>
usingnamespace std;
int main(){
ofstream myfile("oct-24th-test.txt");
if (!myfile.eof()){
myfile << "This is a line.\n";
myfile << "This is another line.\n";
cout<<"adding data success";
myfile.close();
}
else
cout << "Unable to open file";
myfile.close();
cin.get();
return 0;
}
#include <iostream>
#include <fstream>
usingnamespace std;
int main(){
ofstream myfile;
myfile.open("oct-24th-test.txt");
if (!myfile){
cout << "Unable to open file";
exit(1);
}
else{
myfile << "This is a line.\n";
myfile << "This is another line.\n";
cout<<"adding data success";
}
myfile.close();
cin.get();
return 0;
}
those two generate:
adding data success
it means I managed to open the file (and of course wrote the file on "oct-24th-test.txt") but the reality is, I opened the "oct-24th-test.txt" and didn't see the string that I meant to be written by the program.
I really confused with this problem, I seek for the articles in internet about using file in c++ as an input output process all day and follow the code they're using but still I've got no results in my "oct-24th-test.txt" file.
FYI: I'm using visual c++ 2010 express
Please anybody help me, I really appreciate your attention.
Don't check for eof--a stream may fail for other reasons.
You don't need to call close, an fstream is an object that can close itself.
Kiana's commend above is not correct.
Your code should work. Have you tried opening the file in notepad?
The error check can be done like this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include <fstream>
usingnamespace std;
int main(){
ofstream myfile("oct-24th-test.txt");
if (myfile){
myfile << "This is a line.\n";
cout<<"adding data success";
}
else
cerr << "Unable to open file";
cin.get();
return 0;
}
Specifying ios::out is redundant. The object is already an ofstream.
Don't call is_open or close. It goes against the idea of a stream. You should check if it's in a good state as per my example. An fstream object can close itself, this isn't Java.