473,326 Members | 2,090 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

ifstream problems

Hi.

I ran across a bug in one of my problems and after spending some time
tracking it down i found that the problem arose in a piece of code that
essentially did this:

-----------
ifstream in("in.txt"); if(!in) {cout << "error\n";}
in.close(); if(!in) {cout << "error\n";}
in.close(); if(!in) {cout << "error\n";}

in.open("in.txt"); if(!in) {cout << "error\n";}
------------
It reports that opening the file on the last line was unsuccessful as
the last operation, the second in.close() causes an ifstream error.

After digging around in Stroustrups TC++PL i found that putting
'in.clear();' before the in.open() on the last line alleviates this
problem, but is this the right way of refreshing an ifstream that has
had a problem, or may I cause other problems by doing it in this way? Is
there another way I should do it?

regards
/hall
--
<- remove capital x:s from e-mail to reply ->

Jul 22 '05 #1
4 3705
hall wrote in news:iy********************@newsb.telia.net in comp.lang.c++:
Hi.

I ran across a bug in one of my problems and after spending some time
tracking it down i found that the problem arose in a piece of code that
essentially did this:

-----------
ifstream in("in.txt"); if(!in) {cout << "error\n";}
in.close(); if(!in) {cout << "error\n";}
You could prevent this from puting "in" into an error state with:

if ( in.is_open() )
in.close(); if(!in) {cout << "error\n";}
but a second call to close() isn't the only way "in" can become bad.

Also { in.close(); in.clear(); } is probably less expensive and
more Bullet Proof(tm) anyway.

in.open("in.txt"); if(!in) {cout << "error\n";}
------------
It reports that opening the file on the last line was unsuccessful as
the last operation, the second in.close() causes an ifstream error.

After digging around in Stroustrups TC++PL i found that putting
'in.clear();' before the in.open() on the last line alleviates this
problem, but is this the right way of refreshing an ifstream that has
had a problem, or may I cause other problems by doing it in this way?
Is there another way I should do it?


You should consider (if applicable):

int main()
{
// first:
{
ifstream in( "in.txt" );
// whatever
}

// second:
{
ifstream in( "in.txt" );
// different whatever

}
}

The above code reuses 'in' (well its storage anyway) without
all the faffing about, it lets the compiler do it instead.

In theory, your original method may be faster, but the real
cost is probably opening and closing the file, so it unlikly
that the difference can be measured.

If the above isn't applicable (and you can't make it so):

std::ifstream &reopen( std::ifstream &ifs, char const *name )
{
ifs.clear();

ifs.close();
ifs.clear();

ifs.open( name );

return ifs;
}

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 22 '05 #2
Rob Williscroft wrote:
hall wrote in news:iy********************@newsb.telia.net in comp.lang.c++:

Hi.

I ran across a bug in one of my problems and after spending some time
tracking it down i found that the problem arose in a piece of code that
essentially did this:

-----------
ifstream in("in.txt"); if(!in) {cout << "error\n";}
in.close(); if(!in) {cout << "error\n";}

You could prevent this from puting "in" into an error state with:

if ( in.is_open() )

in.close(); if(!in) {cout << "error\n";}

but a second call to close() isn't the only way "in" can become bad.


I am aware of this, and while I can prevent "in" from being closed twise
easily (as it is in a class for formatted output of data) I was more
worried of other causes that may make the ifstream turn bad, such as end
of file.

The class look something like (not tested code)

class Infile {
private:
std::ifstream in;
// ...
public:
void open(std::string s){ in.open(s) };
void close() { in.flush(); in.close() };
// ... methods for reading from file
};

As it is now, opening the ifstream may fail if a user previously have
made something to make the ifstream object to go bad, such as reading
untill end of file, trying to open a nonexisting file and so on.

Also { in.close(); in.clear(); } is probably less expensive and
more Bullet Proof(tm) anyway.

Would this then all be solved by changing the open() method into

void open(){ in.clear(std::string s); in.open(s)}

without giving any unpleasant suprises that i am not aware of (such as
that clear() doesn't fix the ifstream for all bad states)?

My only other idea for solving this was by turning "in" into an ifstream
pointer and create an instance in open() and delete it in close(), but i
thought it would just be too ugly and a better way must exist.


You should consider (if applicable):

int main()
{
// first:
{
ifstream in( "in.txt" );
// whatever
}

// second:
{
ifstream in( "in.txt" );
// different whatever

}
}

The above code reuses 'in' (well its storage anyway) without
all the faffing about, it lets the compiler do it instead.

This, the reusal of storage, i did not know. I'll keep it in mind for
the future, but for this class its not a good idea as i think it is to
be begging for errors to require anyone who uses the code to put each
Infile object in different scopes if he wants to reuse the object.
In theory, your original method may be faster, but the real
cost is probably opening and closing the file, so it unlikly
that the difference can be measured.

If the above isn't applicable (and you can't make it so):

std::ifstream &reopen( std::ifstream &ifs, char const *name )
{
ifs.clear();

ifs.close();
ifs.clear();

ifs.open( name );

return ifs;
}

Now this raises a question. Can I not close a file if
ifstream::good()=false ? Should I also change the close() function in my
class into
void close(){in.flush(); in.clear(); in.close()};
to make sure that the file is actually closed?
Rob.


regards
/hall
--
<- remove capital x:s from e-mail to reply ->

Jul 22 '05 #3
hall wrote in news:p0********************@newsb.telia.net in
comp.lang.c++:
Rob Williscroft wrote:
hall wrote in news:iy********************@newsb.telia.net in
comp.lang.c++:

Hi.

I ran across a bug in one of my problems and after spending some
time tracking it down i found that the problem arose in a piece of
code that essentially did this:

-----------
ifstream in("in.txt"); if(!in) {cout << "error\n";}
in.close(); if(!in) {cout << "error\n";}

You could prevent this from puting "in" into an error state with:

if ( in.is_open() )

in.close(); if(!in) {cout << "error\n";}

but a second call to close() isn't the only way "in" can become bad.


I am aware of this, and while I can prevent "in" from being closed
twise easily (as it is in a class for formatted output of data) I was
more worried of other causes that may make the ifstream turn bad, such
as end of file.

The class look something like (not tested code)

class Infile {
private:
std::ifstream in;
// ...
public:
void open(std::string s){ in.open(s) };
void close() { in.flush(); in.close() };
// ... methods for reading from file
};

As it is now, opening the ifstream may fail if a user previously have
made something to make the ifstream object to go bad, such as reading
untill end of file, trying to open a nonexisting file and so on.
>
Also { in.close(); in.clear(); } is probably less expensive and
more Bullet Proof(tm) anyway.
>


Would this then all be solved by changing the open() method into

void open(){ in.clear(std::string s); in.open(s)}


see below

without giving any unpleasant suprises that i am not aware of (such as
that clear() doesn't fix the ifstream for all bad states)?
It doesn't close the file, and open will fail, if the ifstream is
already open.

My only other idea for solving this was by turning "in" into an
ifstream pointer and create an instance in open() and delete it in
close(), but i thought it would just be too ugly and a better way must
exist.

Ugly dosn't matter, but that you then have to manage the liftime
of the new'd ifstream does, so in this case I'd go with the
close(), clear(), open() method.

[snip]

The above code reuses 'in' (well its storage anyway) without
all the faffing about, it lets the compiler do it instead.


This, the reusal of storage, i did not know. I'll keep it in mind for
the future, but for this class its not a good idea as i think it is to
be begging for errors to require anyone who uses the code to put each
Infile object in different scopes if he wants to reuse the object.
In theory, your original method may be faster, but the real
cost is probably opening and closing the file, so it unlikly
that the difference can be measured.

If the above isn't applicable (and you can't make it so):

std::ifstream &reopen( std::ifstream &ifs, char const *name )
{
ifs.clear();

ifs.close();
ifs.clear();

ifs.open( name );

return ifs;
}


Now this raises a question. Can I not close a file if
ifstream::good()=false ? Should I also change the close() function in
my class into


Yes according to the standard, you can (I just checked)
void close(){in.flush(); in.clear(); in.close()};
to make sure that the file is actually closed?


The flush() isn't needed, close() if indeed the ifstream is open
will do that for you:

void InFile::close()
{
in.close();
in.clear();
}

bool InFile::open( std::strinf const &s )
{
close(); /* InFile:: */
in.open( s.c_str() );
return in.good();
}

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 22 '05 #4

Thanks for your input!
and also, thanks for seeing through the misstakes I made while writing
the code examples. Guess I was a bit to tired last night ;-)

regards
/hall

--
<- remove capital x:s from e-mail to reply ->

Jul 22 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Pete H | last post by:
I am trying to use the same ifstream object to open two files. I will eventually want to open many with a loop. The first file opens fine, but the second has a problem. In my test I try to open two...
1
by: Jim Phelps | last post by:
Hello all, I am in a bit of a pickle using the getline function with an ifstream. It does not seem to work as advertised. Here is my scenario. In a nutshell, my code needs to pick up a fixed...
6
by: Ram Laxman | last post by:
Iam new bie to C++ programming.. I want to write a program which will read the Comma separated values(CSV) file column wise. For example: In a.txt: "TicketNumber","Phone","CarNumber"...
15
by: Christopher Benson-Manica | last post by:
The dumb-o-meter's pegging out today... What, if anything, is wrong with the following code? std::ifstream f( "myfile.txt" ); if( !f ) { cerr << "Couldn't open file\n"; } while( getline(f,s)...
7
by: Hamburgpear | last post by:
Dear All, Is it possible to reset the value of xxx.peek() after it reachs EOF ? Regards HP
3
by: kathleen | last post by:
Hi there, I'm new to this forum & to programming in general, and am really stuck with a piece of buggy code. Can anyone help? I have several problems which may or may not be related. I have...
4
by: marathoner | last post by:
I tried your advice, and replaced "ifstream" with "std::ifstream". I also replaced instances of "ofstream" with "std::ofstream". Those syntax errors were resolved. When I added "std" to the...
3
by: toton | last post by:
Hi, I want to unread a few things while I am reading a file. One solution I know is putback the characters read to the buffer. But as I need frequent moving file pointer , to a few steps back, I...
2
by: mpalomas | last post by:
Hi C++ folks, I have trouble to open files whose path contains non-ascii characters with std::ifstream. For instance let's say i just have a file which has Japanese characters either in the...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.