2 copyright: Steve Dekorte, 2006. All rights reserved.
3 license: See _BSDLicense.txt.
12 // read ------------------------------------------------------
14 size_t UArray_fread_(UArray
*self
, FILE *fp
)
16 size_t itemsRead
= fread(self
->data
, self
->itemSize
, self
->size
, fp
);
17 UArray_setSize_(self
, itemsRead
);
21 long UArray_readFromCStream_(UArray
*self
, FILE *fp
)
23 long totalItemsRead
= 0;
24 long itemsPerBuffer
= 4096 / self
->itemSize
;
25 UArray
*buffer
= UArray_new();
26 UArray_setItemType_(buffer
, self
->itemType
);
27 UArray_setSize_(buffer
, itemsPerBuffer
);
29 if (!fp
) { perror("UArray_readFromCStream_"); return -1; }
31 while(!feof(fp
) && !ferror(fp
))
34 UArray_setSize_(buffer
, itemsPerBuffer
);
35 itemsRead
= UArray_fread_(buffer
, fp
);
37 totalItemsRead
+= itemsRead
;
38 UArray_append_(self
, buffer
);
39 if (itemsRead
!= itemsPerBuffer
) break;
42 if (ferror(fp
)) { perror("UArray_readFromCStream_"); return -1; }
45 return totalItemsRead
;
48 long UArray_readNumberOfItems_fromCStream_(UArray
*self
, size_t size
, FILE *stream
)
51 UArray
*buffer
= UArray_new();
52 UArray_setItemType_(buffer
, self
->itemType
);
53 UArray_setSize_(buffer
, size
);
55 itemsRead
= UArray_fread_(buffer
, stream
);
56 UArray_append_(self
, buffer
);
62 long UArray_readFromFilePath_(UArray
*self
, const UArray
*path
)
66 UArray
*sysPath
= (UArray_itemSize(path
) == 1) ? (UArray
*)path
: UArray_asUTF8(path
);
67 const char *p
= UArray_asCString(sysPath
);
69 //printf("UArray_readFromFilePath_(\"%s\")\n", p);
71 stream
= fopen(p
, "r");
72 if (!stream
) return -1;
73 itemsRead
= UArray_readFromCStream_(self
, stream
);
76 if(sysPath
!= path
) UArray_free(sysPath
);
81 #define CHUNK_SIZE 4096
83 int UArray_readLineFromCStream_(UArray
*self
, FILE *stream
)
85 int readSomething
= 0;
87 if(self
->itemSize
== 1)
89 char *s
= (char *)io_calloc(1, CHUNK_SIZE
);
91 while (fgets(s
, CHUNK_SIZE
, stream
) != NULL
)
93 char *eol1
= strchr(s
, '\n');
94 char *eol2
= strchr(s
, '\r');
98 if (eol1
) { *eol1
= 0; } // remove the \n return character
99 if (eol2
) { *eol2
= 0; } // remove the \r return character
103 UArray_appendCString_(self
, s
);
115 return readSomething
;
118 // write ------------------------------------------------------
120 size_t UArray_fwrite_(const UArray
*self
, size_t size
, FILE *fp
)
122 return fwrite(self
->data
, 1, self
->itemSize
* size
, fp
);
125 long UArray_writeToCStream_(const UArray
*self
, FILE *stream
)
127 size_t totalItemsRead
= UArray_fwrite_(self
, self
->size
, stream
);
128 if (ferror(stream
)) { perror("UArray_readFromCStream_"); return -1; }
129 return totalItemsRead
;
132 long UArray_writeToFilePath_(const UArray
*self
, const UArray
*path
)
134 UArray
*sysPath
= (UArray_itemSize(path
) == 1) ? (UArray
*)path
: UArray_asUTF8(path
);
135 FILE *fp
= fopen(UArray_asCString(sysPath
), "w");
136 long itemsWritten
= -1;
140 itemsWritten
= UArray_writeToCStream_(self
, fp
);