Click to See Complete Forum and Search --> : Detecting EOF in a file stream


they
January 24th, 2005, 09:49 PM
Hi,

I'm trying to figure out how to detect the end of file error flag using managed c++. In unmanaged c++ I could use the following code fragment to detect eof:



while(!fileBeingRead.eof())
{
///code here
}




Obviously the above fragment is executing the while loop until the eof flag is detected in the file being read.

How can I achieve the same result in managed c++?

they
January 25th, 2005, 11:06 PM
I've experimented a bit with trying to detect the end of file. In the following code I am attempting to write to console the lines from a file using a while loop and the ReadLine() function. I am also writing to console the number of lines read. The file looks like this:


Line 1
Line 2
Line 3


Here is the code:



#include "stdafx.h"

#using <mscorlib.dll>


using namespace System;
using namespace System::IO;

int _tmain()
{
FileStream* openFile = new FileStream("g:/files/test.txt", FileMode::Open);

StreamReader* readFile = new StreamReader(openFile);


String* lineRead = " ";


__int32 count = 0;

__int64 pos = 0;
__int64 len = openFile->Length;

while(openFile->Position < openFile->Length)
{

Console::Write(S"Length: ");//write out the length of the file
Console::WriteLine(len);

pos = openFile->Position;//assign the current file position

Console::Write(S"Position: ");//write the current file position
Console::WriteLine(pos);

lineRead = readFile->ReadLine();//read the first line in the file



Console::WriteLine(S"{0}", lineRead);


pos = openFile->Position;//assign the current file position


Console::Write(S"Position: ");//write the current file position
Console::WriteLine(pos);


count++;
}

readFile->Close();
openFile->Close();

Console::Write(S"Number of lines read: ");
Console::WriteLine(count);//write the number of lines read



return 0;
}



Here is the output from the console:

Length: 22
Position: 0
Line 1
Position: 22
Number of Lines Read: 1


When the while loop starts, the position is at 0 as expected but once the first line is read, the position is at 22 and the end of file has been reached, but it seems that the file position should only be at 6 and that the while loop should continue to run. What is going on here? How can I get the while loop to read each line using the ReadLine() function until the end of the file?

Jinto
January 26th, 2005, 07:51 AM
Use the peek method.

while( readFile->Peek() >= 0 ) {
Console::WriteLine( readFile->ReadLine() );
}

they
January 27th, 2005, 08:00 PM
Thanks. That works perfectly.