SE 207 Code Samples

From Gravity
Jump to: navigation, search

Sample File Loader

#include <stdio.h>

int m_datawidth;
int m_dataheight;
int m_datadepth;
unsigned char* m_volumedata;
unsigned char getDataValue(int x, int y, int z);
bool loadDataFile(char* header, char* data);

int main(int argc, char** argv)
{

	loadDataFile("CT_head.hdr", "CT_head.dat");

	// get a sample of our data....

	unsigned char value = getDataValue(m_datawidth/10, m_dataheight/10, m_datadepth/10);
	return 0;
}

bool loadDataFile(char* header, char* data)
{
	FILE* hf = fopen(header, "rt");
	if (hf == NULL)
	{
		fprintf(stderr, "Unable to open header file at %s\n", data);
		return false;
	}
	
	int header_width;
	int header_height;
	int header_depth;

	fscanf(hf, "%d %d %d", &header_width, &header_height, &header_depth);
	fclose(hf);

	FILE* df = fopen(data, "rb");
	if (df == NULL)
	{
		fprintf(stderr, "Unable to open data file at %s\n", data);
		return false;
	}
	int volumesize = header_width * header_height * header_depth;
	unsigned char* volumedata = new unsigned char[volumesize];

	int bytestoread = volumesize;
	int bytesread = 0;
	while (bytestoread > 0)
	{
		int newread;
		newread = fread((void*)&volumedata[bytesread], sizeof(unsigned char), bytestoread, df);
		if (newread <= 0)
		{
			fprintf(stderr, "Error, read %d bytes\n", newread);
			return false;
		}
		else
		{
			bytesread += newread;
			bytestoread -= newread;
		}
	}

	m_datawidth = header_width;
	m_dataheight = header_height;
	m_datadepth = header_depth;
	m_volumedata = volumedata;
}

unsigned char getDataValue(int x, int y, int z)
{
	if (x < m_datawidth && y < m_dataheight && z < m_datadepth)
		return m_volumedata[x + y*m_datawidth + z*m_datawidth*m_dataheight];
	else
		return 0;
}
Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox