summaryrefslogtreecommitdiff
path: root/c,cc/filelib.c
blob: 57a27c3bbeeae3b422437df8ecacad409d75c69f (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
#include "filelib.h"


typedef struct
{
  hFile b_;
  FILE* fp;
} hFile_;

typedef struct
{
  hFile b_;
  gzFile* fp;
} hgzFile;

gzmode(const char* mode)
{
  // TODO
  return true;
}

hgzFile*
gzmakef(char* fname, const char* mode)
{
  hgzFile* hgz = malloc(sizeof(hgzFile));
  hgz->b_.name = fname;
  hgz->b_.gz = true;
  gzFile* fp = malloc(sizeof(gzFile));
  *fp = gzopen(fname, mode);
  hgz->fp = fp;
  return hgz;
}

hFile*
makef(char* fname, const char* mode)
{
  if (endswith(fname, GZIP_EXT))
    return gzmakef(fname, mode);
  hFile_* f = malloc(sizeof(hFile_));
  if (!f) return NULL;
  f->b_.name = fname;
  f->b_.gz = false;
  if (!strcmp(fname, "-")) {
    if (!strcmp(mode, "r") && !strcmp(mode, "r+")) f->fp = stdin;
    else f->fp = stdout;
  } else {
    f->fp = fopen(fname, mode);
  }
  return f;
}

bool
gzwriteln(const char* s, hFile* f)
{
  unsigned len = strlen(s);
  gzwrite(*((hgzFile*)f)->fp, s, len);
  gzwrite(*((hgzFile*)f)->fp, "\n", 1);
  return gzflush(*((hgzFile*)f)->fp, Z_FINISH) == Z_OK;
}

bool
writeln(const char* s, hFile* f)
{
  if (f->gz)
    return gzwriteln(s, f);
  return fputs(s, ((hFile_*)f)->fp)&&fputs("\n", ((hFile_*)f)->fp);
}

bool
gzclosef(hFile* f)
{
  bool ret = gzclose(*((hgzFile*)f)->fp);
  free(((hgzFile*)f)->fp);
  free(f);
  return ret;
}

bool
closef(hFile* f)
{
  if (f->gz)
    return gzclosef(f);
  bool ret = fclose(((hFile_*)f)->fp);
  free(f);
  return ret;
}