magix said:
Hi,
when I read entries in file i.e text file, how can I determine the first
line and the last line ?
I know the first line of entry can be filtered using counter, but how about
the last line of entry in EOF while loop ?
while (! file.eof() )
{
....
}
This sounds a bit like someone's homework to me, so I didn't post complete
code for you... Why? Because, it's rare that one ever needs to know if it
is the last line in the file... If it is, you'll still have some work to
do. If it isn't, good luck.
This is slightly more complete and should get you started. You'll need to
add checks to make sure fopen, etc., actually worked. Also, note that feof
is being used to detect eof.
FILE *file;
strcpy(file,argv[1]);
fopen(file,"rb");
while (!feof(file))
{ /* ... */}
I almost never open a file in text mode, always as binary such as "rb" or
"wb". So, I'm slightly unsure of the following quidance work properly for
text mode...
You can use fseek/ftell to return the size of the file in bytes:
long size;
fseek(file 0L, SEEK_END);
size=ftell(file);
fseek(file 0L, SEEK_SET);
Some C functions to read data from a file tell you how many bytes were read
(i.e., fread, fscanf). If you continually add up the bytes returned by such
a function, the total bytes read in will be equal to the file size upon
reading in the last line. This will occur in your while loop prior to the
check for eof.
Also, those same functions will usually return a specific value when there
is no more input. Depending on which function you choose, the value could
be EOF, NULL or zero. I would suggest reworking the loop into a do{}while
and then using an if()break at the top of the loop to terminate the loop.
The while loop condition could be used to check that your entire read/write
buffer was filled, and the if condition would check for the eof value. If
you don't need to check if your buffer is full, you could still use the
while but change the feof check to instead check for the reading function's
returned value for EOF, NULL, or zero.
Rod Pemberton