ofstream problem

G

Gurikar

Hello,
I have small clafification.

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

void main()
{
ofstream ofs;
ofs<<"before open"<<endl;
ofs.open("\\test.txt");
ofs<<"Test File"<<endl;
ofs.close();
}

when i do this, there is nothing in test.ext file. I do agree that iam
writing something using ofstream before creating file test.txt, but it
should give error. Even after that, iam creating file and opened, when
i write something after, nothing is getting written in that file. It
justs empty? Why is this behaviuor??

Regards
 
C

cadull

I think you will find that ofs.fail() will return true. To enable further
use of the stream call ofs.clear(). This will reset the error flags.

Regards,
cadull
 
C

Chris \( Val \)

| Hello,
| I have small clafification.
|
| #include<fstream>
| #include<iostream>
| using namespace std;
|
| void main()

You should be using a return type of int for the
signature of main().

| {
| ofstream ofs;
| ofs<<"before open"<<endl;

You have just broken the stream state, and it will need
to be reset with the member 'clear()'.

| ofs.open("\\test.txt");
| ofs<<"Test File"<<endl;
| ofs.close();
| }
|
| when i do this, there is nothing in test.ext file. I do agree that iam
| writing something using ofstream before creating file test.txt, but it
| should give error. Even after that, iam creating file and opened, when
| i write something after, nothing is getting written in that file. It
| justs empty? Why is this behaviuor??

Because you broke the stream, and you cannot open a file
with a broken stream until you repair it (reset the stream
state flags), with clear().

Cheers,
Chris Val
 
K

Kristo

Gurikar said:
Hello,
I have small clafification.

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

void main()
{
ofstream ofs;
ofs<<"before open"<<endl;
ofs.open("\\test.txt");
ofs<<"Test File"<<endl;
ofs.close();
}

when i do this, there is nothing in test.ext file. I do agree that
iam writing something using ofstream before creating file test.txt,
but it should give error.

No, it shouldn't. The standard says that if an error occurs while
writing (e.g., writing to a file that isn't open) it sets failbit.
There is no mention of an error message.
Even after that, iam creating file and opened, when i write something
after, nothing is getting written in that file. It justs empty? Why
is this behaviuor??

Once failbit has been set, anything you do with a stream object will
also fail. For this reason, always check that open didn't fail before
you write to a file.

Kristo
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top