#define _GNU_SOURCE 1

#include <hurd.h>
#include <hurd/io.h>
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <error.h>

int main(int argc,char *argv[])
{
	file_t f;
	mach_msg_type_number_t amount;
	char *buf;
	error_t err;

	if(argc != 2) 
		error(1,0,"Usage: %s <filename>",argv[0]);
	
	/* Open file*/
	f = file_name_lookup(argv[1],O_READ,0);
	if(f == MACH_PORT_NULL)
		error(1,errno,"Could not open %s",argv[1]);

	/*Get size of file (buggy!)*/
	err = io_readable(f,&amount);
	if(err)
		error(1,err,"Could not get number of readable bytes");

	printf("\nSize of file = %u",amount);

	/*Create buffer*/
	buf = malloc(amount + 1);
	if(buf == NULL)
		error(1,0,"Out of memory");

	/*Read*/
	err = io_read(f,&buf,&amount,0,amount);
	
	if(err)
		error(1,errno,"Could not read from file %s",argv[1]);
	printf("\nBytes read : %d",amount);
	buf[amount] = '\0';
	mach_port_deallocate(mach_task_self(),f);

	/*Output*/
	printf("%s",buf);
	return 0;
}

