Back to index

im-sdk  12.3.91
util.c
Go to the documentation of this file.
00001 /*
00002  * Copyright 2003 Sun Microsystems Inc.
00003  *
00004  * This is free software; you can redistribute it and/or
00005  * modify it under the terms of the GNU Lesser General Public
00006  * License as published by the Free Software Foundation; either
00007  * version 2 of the License, or (at your option) any later version.
00008  *
00009  * This library is distributed in the hope that it will be useful,
00010  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00011  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00012  * Lesser General Public License for more details.
00013  *
00014  * You should have received a copy of the GNU Lesser General Public
00015  * License along with this library; if not, write to the
00016  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
00017  * Boston, MA 02111-1307, USA.
00018  *
00019  * Authors: Karl Park <karl.park@sun.com>
00020  */
00021 
00022 #include <stdio.h>
00023 #include <stdlib.h>
00024 #include <assert.h>
00025 #include "util.h"
00026 #include <string.h>
00027 
00028 #define SAFEBUF_SIZE 5
00029 
00030 char *
00031 safe_getline (FILE *fp)
00032 {
00033   char *buf, *buf2, *ret;
00034   const size_t bufsize = SAFEBUF_SIZE;
00035   int n = 1;
00036   
00037   assert (fp != NULL);
00038   if (!fp){
00039     /* TO DO: log error */
00040     return NULL;
00041   }
00042 
00043   if (feof (fp) || ferror (fp)){
00044     /* TO DO: log error */
00045     return NULL;
00046   }
00047 
00048   buf = (char *) calloc (bufsize, sizeof (char));
00049   buf2 = buf;
00050   while ((ret = fgets (buf2, bufsize, fp)) != NULL &&
00051         buf2[strlen (buf2) - 1] != '\n'){
00052     buf = (char *) realloc (buf, bufsize * ++n);
00053     buf2 = buf + strlen (buf);
00054   }
00055   if (ret == NULL){
00056     /* TO DO: log error */
00057     return NULL;
00058   }
00059   return buf;
00060 }
00061 
00062 #if 0
00063 int
00064 main (int argc, char **argv)
00065 {
00066   FILE *fp;
00067   char *s;
00068 
00069 
00070   if (argc != 2){
00071     fprintf (stderr, "provide file name\n");
00072     return 0;
00073   }
00074   fp = fopen (argv [1], "r");
00075   while (s = safe_getline (fp)){
00076     printf ("%d byte : %s", strlen (s), s);
00077   }
00078   return 0;
00079 }
00080 #endif
00081 
00082 
00083