三维变长数组读取接口
程序代码:#include <stdio.h>
#include <stdlib.h>
typedef signed char byte;
typedef unsigned char ubyte;
int readInt(ubyte* input, int skip);
short readShort(ubyte* input, int skip);
byte readByte(ubyte* input, int skip);
ubyte* bgLoadResource(char* res_name);
int main(void)
{
byte*** arr = NULL;
ubyte* buffer = NULL;
int i, j, k, len3, len2, len, skip;
len = 0;
skip = 0;
buffer = bgLoadResource("blueguy.bin");
len3 = readShort(buffer, skip);
skip += 2;
arr = malloc(sizeof(ubyte**) * len3); //创建第一维
for (i = 0; i < len3; i++)
{
len2 = readShort(buffer, skip);
skip += 2;
arr[i] = malloc(sizeof(ubyte*) * len2); //创建第二维
for (j = 0; j < len2; j++)
{
len = readShort(buffer, skip);
skip += 2;
arr[i][j] = malloc(sizeof(ubyte) * len); //创建第三维
for (k = 0; k < len; k++)
{
arr[i][j][k] = readByte(buffer, skip);
skip += 1;
}
}
}
return 0;
}
ubyte* bgLoadResource(char* res_name)
{
FILE* fp = NULL;
ubyte* data = NULL;
int size = 0, ret = 0;
if ((fp = fopen(res_name, "rb"))==NULL)
{
printf("File Not Found : %s\n", res_name);
return NULL;
}
fseek(fp, 0L, SEEK_END);
size = ftell(fp);
/* if SEEK_END not supported, use this instead */
/* size = 0;
while (getc(fp) != EOF)
size++;
*/
data = (ubyte*)malloc(sizeof(ubyte) * size);
fseek(fp, 0L, SEEK_SET);
if ((ret = fread(data, size, 1, fp)) != 1)
{
printf("Error reading image data from %s.\n", res_name);
return NULL;
}
fclose(fp);
return data;
}
int readInt(ubyte* input, int skip)
{
int c, c1, c2, c3;
c = input[skip];
c1 = input[skip+1];
c2 = input[skip+2];
c3 = input[skip+3];
return (c3) |
(c2 << 8) |
(c1 << 16) |
(c << 24);
}
short readShort(ubyte* input, int skip)
{
short c, c1;
c = input[skip];
c1 = input[skip+1];
return (c1) |
(c << 8);
}
byte readByte(ubyte* input, int skip)
{
return input[skip];
}
blueguy.bin 每维先存维数, 再存数据。另一种方式,就是将维数单独存在一个文件里。
[ 本帖最后由 新浪 于 2010-8-14 13:31 编辑 ]




