aboutsummaryrefslogtreecommitdiffstats
path: root/test/monniaux/glpk-4.65/src/zlib/zio.c
blob: a55b258a72e0bd5a59a0212bcdcbee74302901f6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/* zio.c (simulation of non-standard low-level i/o functions) */

/* Written by Andrew Makhorin <mao@gnu.org>, April 2011
 * For conditions of distribution and use, see copyright notice in
 * zlib.h */

/* (reserved for copyright notice) */

#include <assert.h>
#include <stdio.h>
#include "zio.h"

static FILE *file[FOPEN_MAX];
static int initialized = 0;

static void initialize(void)
{     int fd;
      assert(!initialized);
      file[0] = stdin;
      file[1] = stdout;
      file[2] = stderr;
      for (fd = 3; fd < FOPEN_MAX; fd++)
         file[fd] = NULL;
      initialized = 1;
      return;
}

int open(const char *path, int oflag, ...)
{     FILE *fp;
      int fd;
      if (!initialized) initialize();
      /* see file gzlib.c, function gz_open */
      if (oflag == O_RDONLY)
         fp = fopen(path, "rb");
      else if (oflag == (O_WRONLY | O_CREAT | O_TRUNC))
         fp = fopen(path, "wb");
      else if (oflag == (O_WRONLY | O_CREAT | O_APPEND))
         fp = fopen(path, "ab");
      else
         assert(oflag != oflag);
      if (fp == NULL)
         return -1;
      for (fd = 0; fd < FOPEN_MAX; fd++)
         if (file[fd] == NULL) break;
      assert(fd < FOPEN_MAX);
      file[fd] = fp;
      return fd;
}

long read(int fd, void *buf, unsigned long nbyte)
{     unsigned long count;
      if (!initialized) initialize();
      assert(0 <= fd && fd < FOPEN_MAX);
      assert(file[fd] != NULL);
      count = fread(buf, 1, nbyte, file[fd]);
      if (ferror(file[fd]))
         return -1;
      return count;
}

long write(int fd, const void *buf, unsigned long nbyte)
{     unsigned long count;
      if (!initialized) initialize();
      assert(0 <= fd && fd < FOPEN_MAX);
      assert(file[fd] != NULL);
      count = fwrite(buf, 1, nbyte, file[fd]);
      if (count != nbyte)
         return -1;
      if (fflush(file[fd]) != 0)
         return -1;
      return count;
}

long lseek(int fd, long offset, int whence)
{     if (!initialized) initialize();
      assert(0 <= fd && fd < FOPEN_MAX);
      assert(file[fd] != NULL);
      if (fseek(file[fd], offset, whence) != 0)
         return -1;
      return ftell(file[fd]);
}

int close(int fd)
{     if (!initialized) initialize();
      assert(0 <= fd && fd < FOPEN_MAX);
      assert(file[fd] != NULL);
      fclose(file[fd]);
      file[fd] = NULL;
      return 0;
}

/* eof */