Reading from file using fgets

You need to check the return value of fgets. If a read has been successful, fgets returns the pointer to the buffer that you passed to it (i.e. string in your example). If the End-of-File is encountered and no characters have been read, fgets returns NULL. Try this: char string[100]; while(fgets(string, 100, fp)) { printf(“%s\n”, … Read more

Read last line of text file

There are two ways: simple and inefficient, or horrendously complicated but efficient. The complicated version assumes a sane encoding. Unless your file is so big that you really can’t afford to read it all, I’d just use: var lastLine = File.ReadLines(“file.txt”).Last(); Note that this uses File.ReadLines, not File.ReadAllLines. If you’re using .NET 3.5 or earlier … Read more