str/str_readline.c

Go to the documentation of this file.
00001 // Copyright (C) 2006-2007 Benedikt Böhm <hollow@gentoo.org>
00002 //
00003 // This program is free software; you can redistribute it and/or
00004 // modify it under the terms of the GNU General Public License
00005 // as published by the Free Software Foundation; either version 2
00006 // of the License, or (at your option) any later version.
00007 //
00008 // This program is distributed in the hope that it will be useful,
00009 // but WITHOUT ANY WARRANTY; without even the implied warranty of
00010 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00011 // GNU General Public License for more details.
00012 //
00013 // You should have received a copy of the GNU General Public License
00014 // along with this program; if not, write to the Free Software
00015 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
00016 
00017 #include <unistd.h>
00018 
00019 #include "mem.h"
00020 #include "str.h"
00021 
00022 int str_readline(int fd, char **line)
00023 {
00024         int chunks = 1, len = 0;
00025         char *buf = mem_alloc(chunks * CHUNKSIZE + 1);
00026         char c;
00027 
00028         while (1) {
00029                 switch(read(fd, &c, 1)) {
00030                 case -1:
00031                         mem_free(buf);
00032                         return -1;
00033 
00034                 case 0:
00035                         goto out;
00036 
00037                 default:
00038                         if (c == '\n' || c == '\r')
00039                                 goto out;
00040 
00041                         if (len >= chunks * CHUNKSIZE) {
00042                                 chunks++;
00043                                 buf = mem_realloc(buf, chunks * CHUNKSIZE + 1);
00044                         }
00045 
00046                         buf[len++] = c;
00047                         break;
00048                 }
00049         }
00050 
00051 out:
00052         *line = buf;
00053         return len;
00054 }

Generated on Tue Jun 19 20:38:27 2007 for lucid by  doxygen 1.5.2