cis_config
AsciiFile.h
1 #include <../tools.h>
2 
4 #ifndef ASCIIFILE_H_
5 #define ASCIIFILE_H_
6 
8 #define LINE_SIZE_MAX 1024*2
9 
11 typedef struct asciiFile_t {
12  const char *filepath;
13  char io_mode[64];
14  char comment[64];
15  char newline[64];
16  FILE *fd;
17 } asciiFile_t;
18 
24 static inline
25 int af_is_open(const asciiFile_t t) {
26  if (t.fd == NULL)
27  return 0;
28  else
29  return 1;
30 };
31 
37 static inline
38 int af_open(asciiFile_t *t) {
39  int ret = -1;
40  if (af_is_open(*t) == 0) {
41  (*t).fd = fopen((*t).filepath, (*t).io_mode);
42  if ((*t).fd != NULL)
43  ret = 0;
44  } else {
45  ret = 0;
46  }
47  return ret;
48 };
49 
55 static inline
56 int af_close(asciiFile_t *t) {
57  int ret;
58  if (af_is_open(*t) == 1) {
59  fclose((*t).fd);
60  (*t).fd = NULL;
61  ret = 0;
62  } else {
63  ret = 0;
64  }
65  return ret;
66 };
67 
74 static inline
75 int af_is_comment(const asciiFile_t t, const char *line) {
76  if (strncmp(line, t.comment, strlen(t.comment)) == 0)
77  return 1;
78  else
79  return 0;
80 };
81 
91 static inline
92 int af_readline_full_norealloc(const asciiFile_t t, char *line, size_t n) {
93  if (af_is_open(t) == 1) {
94  if (fgets(line, (int)n, t.fd) == NULL) {
95  return -1;
96  }
97  int nread = (int)strlen(line);
98  if ((nread < ((int)n - 1)) || (line[nread - 1] == '\n') || (feof(t.fd)))
99  return nread;
100  }
101  return -1;
102 };
103 
114 static inline
115 int af_readline_full(const asciiFile_t t, char **line, size_t *n) {
116  if (af_is_open(t) == 1) {
117  return (int)getline(line, n, t.fd);
118  }
119  return -1;
120 };
121 
128 static inline
129 int af_writeline_full(const asciiFile_t t, const char *line) {
130  if (af_is_open(t) == 1)
131  return (int)fwrite(line, 1, strlen(line), t.fd);
132  return -1;
133 };
134 
143 static inline
144 int af_update(asciiFile_t *t, const char *filepath, const char *io_mode) {
145  t->filepath = filepath;
146  strcpy(t->io_mode, io_mode);
147  return 0;
148 };
149 
161 static inline
162 asciiFile_t asciiFile(const char *filepath, const char *io_mode,
163  const char *comment, const char *newline) {
164  asciiFile_t t;
165  t.fd = NULL;
166  af_update(&t, filepath, io_mode);
167  // Set defaults for optional parameters
168  if (comment == NULL)
169  strcpy(t.comment, "# ");
170  else
171  strcpy(t.comment, comment);
172  if (newline == NULL)
173  strcpy(t.newline, "\n");
174  else
175  strcpy(t.newline, newline);
176  return t;
177 };
178 
179 #endif /*ASCIIFILE_H_*/
const char * filepath
Full path to file.
Definition: AsciiFile.h:12
char comment[64]
Character(s) indicating a comment.
Definition: AsciiFile.h:14
char newline[64]
Character(s) indicating a newline.
Definition: AsciiFile.h:15
char io_mode[64]
I/O mode. &#39;r&#39; for read, &#39;w&#39; for write.
Definition: AsciiFile.h:13
Structure containing information about an ASCII text file.
Definition: AsciiFile.h:11
FILE * fd
File identifier for ASCII file when open.
Definition: AsciiFile.h:16