I’m working with C++, ifstream, and text files. I am looking for the position of the end of each line, because I need read n characters from the end of the line.
Currently, I am reading every byte and testing if it corresponds to the Unix newline character (LF).
Unfortunately, the input is usually long text and my method isn’t fast.
Is there any faster way?
If you are a looking for raw speed, I’d memory map the file and use something like
strchrto find the newline;then so long as
pisn’tNULLor the first character in the memory region, you can just usep[-1]to read the character before the newline.NOTE: if the file could possibly contain
'\0'characters, then you should usememchr. In fact, this may be desirable regardless since it lets you specify the size of the buffer (the memory region).