Problem opening ifstream twice ...

J

Joe

Hello -

I use a ifstream to open a file in my code. I read through it using
getline() and then I close() it. Later in the code I try to open the
same file but it fails. Here is the code:

ifstream InputFile;

char Line[MAXcharLine + 1]; // MAXcharLine = 512

InputFile.open("XXX.dat");

if (InputFile == NULL)
{
// ERROR
}

while (InputFile.getline(Line, MAXcharLine))
{
// DO STUFF
}

InputFile.close();

....

InputFile.open("XXX.dat")

if (InputFile == NULL)
{
// This is where the code fails!
}

What is wrong that it doesn't work? If I don't do the getline() then
it works fine.

Thanks a lot,
Joe
 
S

Sharad Kala

Joe said:
Hello -

I use a ifstream to open a file in my code. I read through it using
getline() and then I close() it. Later in the code I try to open the
same file but it fails. Here is the code:

ifstream InputFile;

char Line[MAXcharLine + 1]; // MAXcharLine = 512

InputFile.open("XXX.dat");

if (InputFile == NULL)
{
// ERROR
}

while (InputFile.getline(Line, MAXcharLine))
{
// DO STUFF
}

InputFile.close();

...

InputFile.open("XXX.dat")

if (InputFile == NULL)
{
// This is where the code fails!
}

What is wrong that it doesn't work? If I don't do the getline() then
it works fine.

The error bit in stream is set after your first file has been read completely
till eof.
This is not cleared automatically and is the duty of the programmer.
So call the clear function on the stream and it should be ok.

Best wishes,
Sharad
 

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

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top