#include "stdafx.h"
#include "apr_file_io.h"
#include "apr_general.h"
#include "apr_strings.h"

static apr_pool_t *context;

void TstDirectory() {
    apr_dir_t *dir;  
    apr_file_t *file = NULL;
    apr_size_t bytes;
    apr_finfo_t dirent;

	printf( "Opening the root directory\n");
    if (apr_dir_open(&dir, "c:\\", context) != APR_SUCCESS) {
		printf( "Could not open the root directory\n");
		exit( -1);
    }

    printf( "Reading the directory\n");
    if ((apr_dir_read( &dirent, APR_FINFO_DIRENT, dir))  != APR_SUCCESS) {
		printf( "Could not read the directory\n");
		exit( -1);
    }
   
    do {
		printf( "Entry is %s\n", dirent.name);
    } while (apr_dir_read( &dirent, 
		APR_FINFO_DIRENT | APR_FINFO_TYPE | APR_FINFO_SIZE | APR_FINFO_MTIME, dir) == APR_SUCCESS);
	return;
}

void TstReadWriteFile() {
	char *buffer;
	char ch;
	int status;
	apr_file_t *fd;
    apr_status_t rv;
    apr_finfo_t finfo;

    buffer = apr_pstrdup(context, "Hello world");
	// Open the file for writing
	printf( "Writing to a file \n");
    apr_file_open( &fd, "c:\\filetest.txt", APR_WRITE | APR_CREATE, -1, context);
	int length = strlen(buffer);
    if( apr_file_write( fd, buffer, &length) != APR_SUCCESS) {
		printf( "Yikes could not write\n");
		exit( -1);
	}
	else {
		printf( "Data (%s) was written to the file\n", buffer);
	}
	apr_file_close( fd);

	// Getting some information about the file
    rv = apr_stat(&finfo, "c:\\filetest.txt", APR_FINFO_NORM, context);
    if (rv != APR_SUCCESS && rv != APR_INCOMPLETE) {
		printf( "Could not get the file information\n");
        exit(1);
    }
	printf( "File size %ld\n", finfo.size);

	// Open the file for reading
	printf( "Reading from the file\n");
    status = apr_file_open( &fd, "c:\\filetest.txt", APR_READ, -1, context);
    while (!status) {
        status = apr_file_getc(&ch, fd);
        if (status == APR_EOF ) {
			printf( "\nAt the end of the file read\n");
		}
        else if (status == APR_SUCCESS) {
			printf( "%c", ch);
		}
    }
	apr_file_close( fd);
	return;
}

void APRFiles() {
	// Create the pool context
    if (apr_pool_create(&context, NULL) != APR_SUCCESS) {
        fprintf(stderr, "Couldn't allocate context.");
        exit(-1);
    }

	TstReadWriteFile();
	TstDirectory();

	apr_pool_destroy( context);
	return;
}