cis_config
AsciiFile.h
1 #include <string.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <stdarg.h>
5 
7 #define ASCIIFILE_INCLUDED
8 
10 #define LINE_SIZE_MAX 1024*2
11 
13 typedef struct asciiFile_t {
14  const char *filepath;
15  char io_mode[64];
16  char comment[64];
17  char newline[64];
18  FILE *fd;
19 } asciiFile_t;
20 
26 static inline
27 int af_is_open(const asciiFile_t t) {
28  if (t.fd == NULL)
29  return 0;
30  else
31  return 1;
32 };
33 
39 static inline
40 int af_open(asciiFile_t *t) {
41  int ret = -1;
42  if (af_is_open(*t) == 0) {
43  (*t).fd = fopen((*t).filepath, (*t).io_mode);
44  if ((*t).fd != NULL)
45  ret = 0;
46  } else {
47  ret = 0;
48  }
49  return ret;
50 };
51 
57 static inline
58 int af_close(asciiFile_t *t) {
59  int ret;
60  if (af_is_open(*t) == 1) {
61  fclose((*t).fd);
62  (*t).fd = NULL;
63  ret = 0;
64  } else {
65  ret = 0;
66  }
67  return ret;
68 };
69 
76 static inline
77 int af_is_comment(const asciiFile_t t, const char *line) {
78  if (strncmp(line, t.comment, strlen(t.comment)) == 0)
79  return 1;
80  else
81  return 0;
82 };
83 
94 static inline
95 int af_readline_full(const asciiFile_t t, char **line, size_t *n) {
96  if (af_is_open(t) == 1) {
97  return getline(line, n, t.fd);
98  }
99  return -1;
100 };
101 
108 static inline
109 int af_writeline_full(const asciiFile_t t, const char *line) {
110  if (af_is_open(t) == 1)
111  return fwrite(line, 1, strlen(line), t.fd);
112  return -1;
113 };
114 
126 static inline
127 asciiFile_t asciiFile(const char *filepath, const char *io_mode,
128  const char *comment, const char *newline) {
129  asciiFile_t t;
130  t.fd = NULL;
131  t.filepath = filepath;
132  strcpy(t.io_mode, io_mode);
133  // Set defaults for optional parameters
134  if (comment == NULL)
135  strcpy(t.comment, "# ");
136  else
137  strcpy(t.comment, comment);
138  if (newline == NULL)
139  strcpy(t.newline, "\n");
140  else
141  strcpy(t.newline, newline);
142  return t;
143 };
144 
const char * filepath
Full path to file.
Definition: AsciiFile.h:14
char comment[64]
Character(s) indicating a comment.
Definition: AsciiFile.h:16
char newline[64]
Character(s) indicating a newline.
Definition: AsciiFile.h:17
char io_mode[64]
I/O mode. &#39;r&#39; for read, &#39;w&#39; for write.
Definition: AsciiFile.h:15
Structure containing information about an ASCII text file.
Definition: AsciiFile.h:13
FILE * fd
File identifier for ASCII file when open.
Definition: AsciiFile.h:18