33 #include "io_lib_config.h"
40 #include <sys/types.h>
62 static mFILE *m_channel[3];
73 static char *mfload(FILE *fp,
const char *fn,
size_t *size,
int binary) {
76 size_t allocated = 0, used = 0;
81 _setmode(_fileno(fp), _O_BINARY);
83 _setmode(_fileno(fp), _O_TEXT);
86 if (fn && -1 != stat(fn, &sb)) {
87 data = malloc(allocated = sb.st_size);
95 if (used + bufsize > allocated) {
97 data = realloc(data, allocated);
99 len = fread(data + used, 1, allocated - used, fp);
102 }
while (!feof(fp) && (fn == NULL || used < sb.st_size));
119 if (NULL == m_channel[0])
return NULL;
120 m_channel[0]->
fp = stdin;
124 static void init_mstdin(
void) {
125 static int done_stdin = 0;
129 m_channel[0]->
data = mfload(stdin, NULL, &m_channel[0]->size, 1);
144 if (NULL == m_channel[1])
return NULL;
145 m_channel[1]->
fp = stdout;
160 if (NULL == m_channel[2])
return NULL;
161 m_channel[2]->
fp = stderr;
172 if (NULL == mf)
return NULL;
213 if (NULL == (mf =
mfreopen(path, mode_str, fp)))
229 int r = 0, w = 0, a = 0, b = 0, x = 0, mode = 0;
237 if (strchr(mode_str,
'r'))
239 if (strchr(mode_str,
'w'))
241 if (strchr(mode_str,
'a'))
243 if (strchr(mode_str,
'b'))
245 if (strchr(mode_str,
'x'))
247 if (strchr(mode_str,
'+')) {
255 if (NULL == mf)
return NULL;
257 mf->
data = mfload(fp, path, &mf->
size, b);
265 if (NULL == mf)
return NULL;
267 fprintf(stderr,
"Must specify either r, w or a for mode\n");
293 if (NULL == (fp = fopen(path, mode)))
360 if (!mf)
return NULL;
364 if (NULL != size_out) *size_out = mf->
size;
416 mf->
size = offset != -1 ? offset : mf->
offset;
431 char *cptr = (
char *)ptr;
433 if (mf == m_channel[0]) init_mstdin();
447 if (len != size * nmemb) {
465 void * new_data = realloc(mf->
data, new_alloced);
466 if (NULL == new_data)
return 0;
476 memcpy(&mf->
data[mf->
offset], ptr, size * nmemb);
477 mf->
offset += size * nmemb;
485 if (mf == m_channel[0]) init_mstdin();
507 if (mf == m_channel[0]) init_mstdin();
509 for (i = 0; i < size-1;) {
539 if (mf == m_channel[1] || mf == m_channel[2]) {
544 if (0 != fflush(mf->
fp))
561 if (0 != fflush(mf->
fp))
564 if (ftell(mf->
fp) != -1 &&
565 ftruncate(fileno(mf->
fp), ftell(mf->
fp)) == -1)
584 est_length =
vflen(fmt, args);
588 void * new_data = realloc(mf->
data, new_alloced);
589 if (NULL == new_data)
return -1;
595 ret = vsprintf(&mf->
data[mf->
offset], fmt, args);
604 if (mf->
fp == stderr) {
606 if (0 !=
mfflush(mf))
return -1;
625 for (p1 = p2 = 1; p1 < mf->
size; p1++, p2++) {
626 if (mf->
data[p1] ==
'\n' && mf->
data[p1-1] ==
'\r') {