Two ways:
1) read all lines in the file, keep remembering the last one.
2) Seek to the end of the file and read one character (or a small block) at a time from the end until you find a newline.
1) is obviously inefficient for large files but is very simple, 2) would be the correct way to do it.
What if a line is more than 50 characters long? You can't put 256 characters into a size 50 character array. Also, that uses the first method, the OP has decided on the second method.
Modify your code? If you mean comment it out and write the correct code under it then sure. The point is, that code uses the first method, and the OP wants to use the second method; they're completely different.
@L B
The ungetc() method doesn't work like that. (I suppose it could, but the standard does not require it, and no library I know of does it.)
@qabil
Don't loop on eof().
@asdfg
Of the two methods given you, the first is by far the easiest with the fewest caveats. The only thing you would want to consider is any trailing empty lines in the file. (Most text files have an empty line as the last line in the file. The C and C++ standards even recommend it for source files.)
The second option requires some careful programming and bookkeeping to make it work right. Unless you know that you will be using this on super ultra huge files, go with the first option -- it is fast enough.
(I am currently moving and so have limited time for posting stuff, so I don't know if I can get you an example of doing the second option properly any time soon.)
I would also go with the first solution, but as an alternative you could use mmap and used std::find with the reverse_iterator adapter to look for the first '\n' starting from the end of the file.