James C
James C

Reputation: 919

Problems with creating text files with ofstream in C++

I am following a C++ textbook, currently at the part that is dealing with ofstream and ifstream. I have typed a couple of examples in the same main() function of a project ( CodeBlocks 13.12 ).

The problem is that some of the code at the beginning works fine, and the rest of it doesn't. I tried to explain it below, after the code.:

ofstream outfile("MyFile.dat");  

if (!outfile) 
{
cout << "Couldn’t open the file!" << endl;
}

outfile << "Hi" << endl;
outfile.close();

ofstream outfile2("MyFile.dat", ios_base::app); 
outfile2 << "Hi again" << endl; 
outfile2.close();


ifstream infile("MyFile.dat");
if (infile.fail())
{
cout << "Couldn't open the file!" << endl;
return 0;
}
infile.close();
ofstream outfile3("MyFile.dat", ios_base::app);
outfile3 << "Hey" << endl;
outfile3.close();


string word;
ifstream infile2("MyFile.dat");
infile2 >> word; 
cout << word << endl; // "Hi" gets printed, I suppose it only prints 1st line ?
infile2.close();


ifstream infile3("MyFile.dat");
if (!infile3.fail())
{
cout << endl << "The file already exists!" << endl;
return 0;
}
infile3.close();
ofstream outfile4("MyFile.dat");
outfile4 << "Hi Foo" << endl; 
outfile4.close();
// this piece of code erases everything in MyFile.dat - why ?


ofstream outfile5("outfile5.txt");
outfile5 << "Lookit me! I’m in a file!" << endl;
int x = 200;
outfile5 << x << endl;
outfile5.close();

When the code executes, the only created file is MyFile.dat and its contents are

Hi
Hi again
Hey

"Hi Foo" doesn't get written to the file and "outfile5.txt" is not created.

Can someone explain me why part of the code doesn't work ? And how to correct it, or what to keep an eye on for future reference ?

Upvotes: 0

Views: 303

Answers (1)

vsoftco
vsoftco

Reputation: 56557

In

ifstream infile3("MyFile.dat");
if (!infile3.fail())
{
    cout << endl << "The file already exists!" << endl;
    return 0;
}

you exit (return 0) whenever testing for the successful opening of "MyFile.dat".

In

ofstream outfile4("MyFile.dat");
outfile4 << "Hi Foo" << endl; 
outfile4.close();
// this piece of code erases everything in MyFile.dat - why ?

the content of "MyFile.dat" is being erased, since by default you open the stream for rewriting, and not appending. If you want to append, use

outfile.open("MyFile.txt", std::ios_base::app);

Upvotes: 4

Related Questions