comparison src/dmfile.c @ 1473:c543f5ae92d5

Cleanup dmReadDataFile() helper function.
author Matti Hamalainen <ccr@tnsp.org>
date Fri, 11 May 2018 01:59:37 +0300
parents e06abfde6c39
children 6b1f41ca300a
comparison
equal deleted inserted replaced
1472:b9d3577d8290 1473:c543f5ae92d5
59 59
60 60
61 #define BUF_SIZE_INITIAL (16*1024) 61 #define BUF_SIZE_INITIAL (16*1024)
62 #define BUF_SIZE_GROW (4*1024) 62 #define BUF_SIZE_GROW (4*1024)
63 63
64 int dmReadDataFile(FILE *inFile, const char *filename, Uint8 **pbuf, size_t *pbufSize) 64 int dmReadDataFile(FILE *ffh, const char *filename, Uint8 **pbuf, size_t *pbufSize)
65 { 65 {
66 FILE *f; 66 FILE *fh = NULL;
67 int res = DMERR_OK; 67 int res = DMERR_OK;
68 Uint8 *dataBuf = NULL; 68 Uint8 *dataBuf = NULL;
69 size_t readSize, dataSize, dataRead, dataPos; 69 size_t readSize, dataSize, dataRead, dataPos;
70 70
71 if (inFile != NULL) 71 if (ffh != NULL)
72 f = inFile; 72 fh = ffh;
73 else 73 else
74 if (filename != NULL) 74 if (filename != NULL)
75 { 75 {
76 if ((f = fopen(filename, "rb")) == NULL) 76 if ((fh = fopen(filename, "rb")) == NULL)
77 { 77 {
78 return dmError(DMERR_FOPEN, 78 return dmError(DMERR_FOPEN,
79 "Could not open '%s' for reading.\n", filename); 79 "Could not open '%s' for reading.\n", filename);
80 } 80 }
81 } 81 }
82 else 82
83 if (fh == NULL)
83 { 84 {
84 return dmError(DMERR_NULLPTR, 85 return dmError(DMERR_NULLPTR,
85 "NULL filename and stream pointers.\n"); 86 "NULL filename and stream pointers.\n");
86 } 87 }
87 88
92 res = dmError(DMERR_MALLOC, 93 res = dmError(DMERR_MALLOC,
93 "Error allocating memory for data, %d bytes.\n", dataSize); 94 "Error allocating memory for data, %d bytes.\n", dataSize);
94 goto error; 95 goto error;
95 } 96 }
96 97
97 dataPos = 0; 98 // Read the data
98 dataRead = 0; 99 dataPos = dataRead = 0;
99 100 while (!feof(fh) && !ferror(fh))
100 while (!feof(f) && !ferror(f))
101 { 101 {
102 size_t read = fread(dataBuf + dataPos, 1, readSize, f); 102 size_t read = fread(dataBuf + dataPos, 1, readSize, fh);
103 dataPos += read; 103 dataPos += read;
104 dataRead += read; 104 dataRead += read;
105 105
106 if (dataRead >= dataSize) 106 if (dataRead >= dataSize)
107 { 107 {
121 121
122 *pbufSize = dataRead; 122 *pbufSize = dataRead;
123 *pbuf = dataBuf; 123 *pbuf = dataBuf;
124 124
125 error: 125 error:
126 if (f != inFile) 126 if (ffh != fh)
127 fclose(f); 127 fclose(fh);
128 128
129 return res; 129 return res;
130 } 130 }