Reputation: 105
I want a way to check when the last line of the file is being read. Is there a way I can do this?
Upvotes: 1
Views: 2106
Reputation: 93172
Yes. Attempt to read another line. If that yields an end-of-file condition, then the line you read before was the last line. There are kinda-sorta-maybe ways to get similar results without trying to read another line but they only work under specific conditions and are prone to race conditions.
If this is too complex, consider writing a wrapper around the function you use to read a line that buffers one line for you. This wrapper can then pretend to know that it reached the end of file easily by checking if it is able to read ahead another line.
Upvotes: 5
Reputation: 29754
If file can be fseeked then it is possible to use fseek to do that if you know what is the maximum line length of this file.
ssize_t len;
char buf[max_len + 1];
//remember current position before fseek
currp = ftell(fd);
// set the file pointer to the beginning of the last line
fseek(fd, -max_len, SEEK_END);
// compare current position
if (ftell(fd) <= currp)
{
// this might be the last line
// now we have to check if there is only single '\n'
// read file block
len = read(fd, buf, max_len);
if (len == -1)
{
perror("read failed");
return -1;
}
buf[len] = '\0';
if (strchr(buf, '\n') == strrchr(buf, '\n'))
{
// single newline was found
// it is the last line
// revert the pointer changes
fseek(fd, currp, SEEK_SET);
return 0;
}
}
You must be aware of the possibility of the race conditions.
Upvotes: 0
Reputation: 16550
A way to tell if the line just read is the last line in the file...
FILE *fp = fopen( filename, "r" );
fseek( fp, 0, SEEK_END );
long filesize = ftell( fd );
fseek( fp, 0, SEEK_SET);
....
fgets( buffer, sizeof buffer, fp);
if (filesize == ftell(fp) )
{
// then last line is read
}
Naturally, appropriate error checking needs to be performed at each system function call; however, the above will let the code know when the last line is read.
Note: the above method will not work for pipes, fifos, and when accessing an external bus.
Upvotes: 1
Reputation: 727077
No, there is no general way to know if the line being read is the last line of the file.
The reason is that line number is determined exclusively by the data in your file. It is impossible to know on which line is your reader until you have read the relevant portion of the data, and checked it for presence of end-of-line markers.
Two special cases when you can tell the line number and even navigate to a specific line is when all lines in your file are as follows:
Upvotes: 2