Back to index

glibc  2.9
pwrite.c
Go to the documentation of this file.
00001 /* Write block to given position in file without changing file pointer.
00002    POSIX version.
00003    Copyright (C) 1997, 1998, 1999, 2002 Free Software Foundation, Inc.
00004    This file is part of the GNU C Library.
00005    Contributed by Ulrich Drepper <drepper@cygnus.com>, 1997.
00006 
00007    The GNU C Library is free software; you can redistribute it and/or
00008    modify it under the terms of the GNU Lesser General Public
00009    License as published by the Free Software Foundation; either
00010    version 2.1 of the License, or (at your option) any later version.
00011 
00012    The GNU C Library is distributed in the hope that it will be useful,
00013    but WITHOUT ANY WARRANTY; without even the implied warranty of
00014    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015    Lesser General Public License for more details.
00016 
00017    You should have received a copy of the GNU Lesser General Public
00018    License along with the GNU C Library; if not, write to the Free
00019    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
00020    02111-1307 USA.  */
00021 
00022 #include <errno.h>
00023 #include <unistd.h>
00024 
00025 /* Note: This implementation of pwrite is not multithread-safe.  */
00026 
00027 ssize_t
00028 __libc_pwrite (int fd, const void *buf, size_t nbyte, off_t offset)
00029 {
00030   /* Since we must not change the file pointer preserve the value so that
00031      we can restore it later.  */
00032   int save_errno;
00033   ssize_t result;
00034   off_t old_offset = __libc_lseek (fd, 0, SEEK_CUR);
00035   if (old_offset == (off_t) -1)
00036     return -1;
00037 
00038   /* Set to wanted position.  */
00039   if (__libc_lseek (fd, offset, SEEK_SET) == (off_t) -1)
00040     return -1;
00041 
00042   /* Write out the data.  */
00043   result = __libc_write (fd, buf, nbyte);
00044 
00045   /* Now we have to restore the position.  If this fails we have to
00046      return this as an error.  But if the writing also failed we
00047      return this error.  */
00048   save_errno = errno;
00049   if (__libc_lseek (fd, old_offset, SEEK_SET) == (off_t) -1)
00050     {
00051       if (result == -1)
00052        __set_errno (save_errno);
00053       return -1;
00054     }
00055   __set_errno (save_errno);
00056 
00057   return result;
00058 }
00059 
00060 #ifndef __libc_pwrite
00061 strong_alias (__libc_pwrite, __pwrite)
00062 weak_alias (__libc_pwrite, pwrite)
00063 #endif