home *** CD-ROM | disk | FTP | other *** search
/ Programmer 7500 / MAX_PROGRAMMERS.iso / CLIPPER / MISC / EMXLIB8F.ZIP / EMX / LIB / IO / FSEEK.C < prev    next >
Encoding:
C/C++ Source or Header  |  1993-01-02  |  2.0 KB  |  69 lines

  1. /* fseek.c (emx+gcc) -- Copyright (c) 1990-1993 by Eberhard Mattes */
  2.  
  3. #include <sys/emx.h>
  4. #include <stdio.h>
  5. #include <io.h>
  6. #include <errno.h>
  7.  
  8. int fseek (FILE *stream, long offset, int origin)
  9. {
  10.   long pos;
  11.  
  12.   if (!(stream->flags & _IOOPEN) || origin < 0 || origin > 2)
  13.     {
  14.       errno = EINVAL;
  15.       return (EOF);
  16.     }
  17.  
  18.   /* fflush() is not required if all of the following conditions are met: */
  19.   /* - stream is a read-only file                                         */
  20.   /* - _IOREREAD not set (that is, ungetc() has not been called)          */
  21.   /* - stream is buffered                                                 */
  22.   /* - new position is within buffer                                      */
  23.  
  24.   if ((stream->flags & (_IORW|_IOREAD|_IOWRT|_IOREREAD)) == _IOREAD
  25.       && bbuf (stream))
  26.     {
  27.       long file_pos, cur_pos, end_pos, buf_pos;
  28.  
  29.       file_pos = lseek (stream->handle, 0L, SEEK_CUR);
  30.       if (file_pos == -1)
  31.         return (EOF);
  32.       cur_pos = file_pos - stream->rcount;
  33.       if (origin == SEEK_CUR)
  34.         {
  35.           offset += cur_pos;
  36.           origin = SEEK_SET;
  37.         }
  38.       else if (origin == SEEK_END)
  39.         {
  40.           end_pos = lseek (stream->handle, 0L, SEEK_END);
  41.           lseek (stream->handle, file_pos, SEEK_SET);
  42.           if (end_pos == -1)
  43.             return (EOF);
  44.           offset += end_pos;
  45.           origin = SEEK_SET;
  46.         }
  47.       buf_pos = cur_pos - (stream->ptr - stream->buffer);
  48.       if (offset >= buf_pos && offset < file_pos)
  49.         {
  50.           stream->ptr = stream->buffer + (offset - buf_pos);
  51.           stream->rcount = file_pos - offset;
  52.           stream->flags &= ~_IOEOF;
  53.           return (0);
  54.         }
  55.     }
  56.   fflush (stream);
  57.   stream->flags &= ~_IOEOF;
  58.   if (stream->flags & _IORW)
  59.     stream->flags &= ~(_IOREAD|_IOWRT);
  60.   if (origin == SEEK_CUR)
  61.     {
  62.       pos = ftell (stream);
  63.       if (pos == -1L) return (EOF);
  64.       offset += pos;
  65.       origin = SEEK_SET;
  66.     }
  67.   return ((lseek (stream->handle, offset, origin) == -1L) ? EOF : 0);
  68. }
  69.