about summary refs log tree commit diff
path: root/lib/pmfileio.c
diff options
context:
space:
mode:
authorgiraffedata <giraffedata@9d0c8265-081b-0410-96cb-a4ca84ce46f8>2022-05-21 23:51:29 +0000
committergiraffedata <giraffedata@9d0c8265-081b-0410-96cb-a4ca84ce46f8>2022-05-21 23:51:29 +0000
commitaa318b918635c4bdbe3f70f549d732d0a501782e (patch)
tree168fbf5094cafda5d3d3bb7acf2ddf5a114257a9 /lib/pmfileio.c
parent277450e08e8d77aed07b5e225702eed7bf700f6e (diff)
downloadnetpbm-mirror-aa318b918635c4bdbe3f70f549d732d0a501782e.tar.gz
netpbm-mirror-aa318b918635c4bdbe3f70f549d732d0a501782e.tar.xz
netpbm-mirror-aa318b918635c4bdbe3f70f549d732d0a501782e.zip
Add pm_readfile
git-svn-id: http://svn.code.sf.net/p/netpbm/code/trunk@4341 9d0c8265-081b-0410-96cb-a4ca84ce46f8
Diffstat (limited to 'lib/pmfileio.c')
-rw-r--r--lib/pmfileio.c48
1 files changed, 48 insertions, 0 deletions
diff --git a/lib/pmfileio.c b/lib/pmfileio.c
index 1ed71f18..9ff4b99a 100644
--- a/lib/pmfileio.c
+++ b/lib/pmfileio.c
@@ -939,6 +939,54 @@ pm_getline(FILE *   const ifP,
 
 
 
+void
+pm_readfile(FILE *                 const fileP,
+            const unsigned char ** const bytesP,
+            size_t *               const szP) {
+
+    unsigned char * buf;
+    size_t allocatedSz;
+    size_t szSoFar;
+    size_t chunkSz;
+    bool eof;
+
+    for (szSoFar = 0, buf = NULL, allocatedSz = 0, chunkSz = 4096,
+             eof = false;
+         !eof; ) {
+
+        size_t bytesReadCt;
+
+        if (szSoFar + chunkSz > allocatedSz) {
+            allocatedSz = szSoFar + chunkSz;
+            REALLOCARRAY(buf, allocatedSz);
+
+            if (!buf) {
+                pm_error("Failed to get memory for %lu byte input buffer",
+                         allocatedSz);
+            }
+        }
+        bytesReadCt = fread(buf + szSoFar, 1, chunkSz, fileP);
+
+        if (ferror(fileP))
+            pm_error("Failed to read input from file");
+
+        szSoFar += bytesReadCt;
+
+        if (bytesReadCt < chunkSz)
+            eof = true;
+        else {
+            /* Double buffer and read size up to 1 MiB */
+            if (szSoFar <= 1024*1024)
+                chunkSz = szSoFar;
+        }
+    }
+
+    *bytesP = buf;
+    *szP    = szSoFar;
+}
+
+
+
 union cheat {
     uint32_t l;
     short s;