You are not logged in.

#1 2012-05-02 17:24:14

Bellum
Member
Registered: 2011-08-24
Posts: 230

binio code review

I've finally gotten around to working through this concept. It works, but if anyone would be willing to work through this and tell me where I've been bad I would really appreciate it. Teaching yourself has its limitations.

#include "binio.h"

int main(void)
{
	point *plots;
	if((plots = ten_points()) == NULL)
	{
		fprintf(stderr, "failed to allocate mem\n");
		return EXIT_FAILURE;
	}
	int size = 10;

	if(save_points(&plots, size) != 0)
	{
		fprintf(stderr, "failed to write data\n");
		return EXIT_FAILURE;
	}
	free(plots);
	plots = NULL;

	if((size = load_points(&plots)) != size)
	{
		fprintf(stderr, "read failed\n");
		return EXIT_FAILURE;
	}
	for(int i = 0; i < size; i++)
	{
		printf("(%d,%d)\n", plots[i].x, plots[i].y);
	}

	return EXIT_SUCCESS;
}

point *ten_points(void)
{
	point *points = malloc(sizeof(point) * 10);
	for(int i = 0; i < 10; i++)
	{
		points[i].x = i;
		points[i].y = i+1;
	}
	return points;
}

int save_points(point **points, int size)
{
	FILE *save_file;
	save_file = fopen("data", "w");
	if(!save_file)
		return 1;
	if(fwrite(*points, sizeof(point), size, save_file) < size)
	{
		fclose(save_file);
		return 1;
	}
	fclose(save_file);
	return 0;
}

int load_points(point **points)
{
	int size;
	FILE *load_file = fopen("data", "r");
	struct stat load_file_stats;

	if(stat("data", &load_file_stats) != 0)
	{
		fclose(load_file);
		return -1;
	}
	*points = malloc(load_file_stats.st_size);
	size = (load_file_stats.st_size / sizeof(point));
	if(fread(*points, sizeof(point), size, load_file) != size)
	{
		fclose(load_file);
		return -1;
	}
	fclose(load_file);
	return size;
}

Offline

#2 2012-05-03 19:18:11

prasinoulhs
Member
From: Greece
Registered: 2011-10-30
Posts: 53

Re: binio code review

When you call malloc you should check if it succeded, upon failure malloc returns a NULL pointer . The same applies when opening files always check if you got a file descriptor or a NULL pointer (you do that when opening the file to write but not when opening to read). With a quick search i found that you are trying to read/write binary data, if that is correct you should check the "b" option that can be passed to fopen.

Offline

#3 2012-05-03 20:06:32

Bellum
Member
Registered: 2011-08-24
Posts: 230

Re: binio code review

Jeez, thanks. Error checking in C is hard compared to other languages!

Is it normal to pass "b" to fopen in *nix? Man page says it doesn't do anything. I suppose it's the best thing to do for the sake of portability.

Offline

Board footer

Powered by FluxBB