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 strchr
to find the newline;
p = strchr(line_start, '\n');
then so long as p
isn't NULL
or the first character in the memory region, you can just use p[-1]
to read the character before the newline.
NOTE: if the file could possibly contain '\0'
characters, then you should use memchr
. In fact, this may be desirable regardless since it lets you specify the size of the buffer (the memory region).