Back to index

glibc  2.9
fgetpwent.c
Go to the documentation of this file.
00001 /* Copyright (C) 1991,1996,1997,1999,2000,2002 Free Software Foundation, Inc.
00002    This file is part of the GNU C Library.
00003 
00004    The GNU C Library 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.1 of the License, or (at your option) any later version.
00008 
00009    The GNU C 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 the GNU C Library; if not, write to the Free
00016    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
00017    02111-1307 USA.  */
00018 
00019 #include <errno.h>
00020 #include <bits/libc-lock.h>
00021 #include <pwd.h>
00022 #include <stdio.h>
00023 #include <stdlib.h>
00024 
00025 
00026 /* We need to protect the dynamic buffer handling.  */
00027 __libc_lock_define_initialized (static, lock);
00028 
00029 libc_freeres_ptr (static char *buffer);
00030 
00031 /* Read one entry from the given stream.  */
00032 struct passwd *
00033 fgetpwent (FILE *stream)
00034 {
00035   static size_t buffer_size;
00036   static struct passwd resbuf;
00037   fpos_t pos;
00038   struct passwd *result;
00039   int save;
00040 
00041   if (fgetpos (stream, &pos) != 0)
00042     return NULL;
00043 
00044   /* Get lock.  */
00045   __libc_lock_lock (lock);
00046 
00047   /* Allocate buffer if not yet available.  */
00048   if (buffer == NULL)
00049     {
00050       buffer_size = NSS_BUFLEN_PASSWD;
00051       buffer = malloc (buffer_size);
00052     }
00053 
00054   while (buffer != NULL
00055         && (__fgetpwent_r (stream, &resbuf, buffer, buffer_size, &result)
00056             == ERANGE))
00057     {
00058       char *new_buf;
00059       buffer_size += NSS_BUFLEN_PASSWD;
00060       new_buf = realloc (buffer, buffer_size);
00061       if (new_buf == NULL)
00062        {
00063          /* We are out of memory.  Free the current buffer so that the
00064             process gets a chance for a normal termination.  */
00065          save = errno;
00066          free (buffer);
00067          __set_errno (save);
00068        }
00069       buffer = new_buf;
00070 
00071       /* Reset the stream.  */
00072       if (fsetpos (stream, &pos) != 0)
00073        buffer = NULL;
00074     }
00075 
00076   if (buffer == NULL)
00077     result = NULL;
00078 
00079   /* Release lock.  Preserve error value.  */
00080   save = errno;
00081   __libc_lock_unlock (lock);
00082   __set_errno (save);
00083 
00084   return result;
00085 }