glVertex  5.5.2
glvertex_io.h
Go to the documentation of this file.
1 // (c) by Stefan Roettger, licensed under MIT license
2 
5 #ifndef GLVERTEX_IO_H
6 #define GLVERTEX_IO_H
7 
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 
12 inline unsigned char *lglReadFiled(FILE *file, size_t *bytes, const size_t blocksize=1<<20)
13 {
14  unsigned char *data, *data2;
15  size_t cnt, blkcnt;
16 
17  data = NULL;
18  *bytes = cnt = 0;
19 
20  do
21  {
22  if (data == NULL)
23  {
24  if ((data=(unsigned char *)malloc(blocksize)) == NULL) return(NULL);
25  }
26  else
27  {
28  if ((data2=(unsigned char *)realloc(data, cnt+blocksize)) == NULL) {free(data); return(NULL);}
29  data = data2;
30  }
31  blkcnt = fread(&data[cnt], 1, blocksize, file);
32  cnt += blkcnt;
33  }
34  while (blkcnt == blocksize);
35 
36  if (cnt == 0)
37  {
38  free(data);
39  return(NULL);
40  }
41 
42  if ((data2=(unsigned char *)realloc(data, cnt)) == NULL) {free(data); return(NULL);}
43  else data = data2;
44 
45  *bytes = cnt;
46 
47  return(data);
48 }
49 
50 inline unsigned char *lglReadFile(const char *filename, size_t *bytes)
51 {
52  FILE *file;
53  unsigned char *data;
54 
55  if ((file=fopen(filename, "rb"))==NULL) return(NULL);
56  data = lglReadFiled(file, bytes);
57  fclose(file);
58 
59  return(data);
60 }
61 
62 inline std::string lglReadTextFile(const char *filename)
63 {
64  std::string text;
65 
66  unsigned char *data;
67  size_t bytes;
68 
69  data = lglReadFile(filename, &bytes);
70 
71  if (data)
72  {
73  text = std::string((char *)data, bytes);
74  free(data);
75  }
76 
77  return(text);
78 }
79 
80 inline std::string lglReadTextFile(const std::string &filename)
81 {
82  return(lglReadTextFile(filename.c_str()));
83 }
84 
85 inline bool lglWriteFile(const char *filename, unsigned char *chunk, size_t bytes)
86 {
87  FILE *file;
88  size_t count;
89 
90  if ((file=fopen(filename, "wb"))==NULL) return(false);
91  count = fwrite((void *)chunk, 1, bytes, file);
92  fclose(file);
93 
94  return(count == bytes);
95 }
96 
97 inline bool lglWriteTextFile(const char *filename, const std::string &text)
98 {
99  return(lglWriteFile(filename, (unsigned char *)text.c_str(), text.size()));
100 }
101 
102 inline bool lglWriteTextFile(const std::string &filename, const std::string &text)
103 {
104  return(lglWriteTextFile(filename.c_str(), text));
105 }
106 
107 #endif