How about this logic: you search the string for the first '\n', then check the previous symbol. This will only be slow for files with very long first line (but not for long files with normal lines). This is unavoidable since all other operations are also slow for such files.