Note that starting with commit 67a472d71c98 you can use pg_get_line andnot worry about the hard part of this anymore :-)
-- Álvaro Herrera https://www.2ndQuadrant.com/PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services