fileHandling.c 1.84 KB
Newer Older
Celine Mercier committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
/**
 * FileName:    fileHandling.c
 * Authors:      Tiayyba Riaz, Celine Mercier
 * Description: C file for file handling functions
 * **/

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#include "../libutils/utilities.h"

/*
 * Function Name: fileOpen(char* fileName, BOOL abortOnError)
 * Description:   Opens the file and returns the pointer to file object
 */
FILE *file_open(char* fileName, BOOL abortOnError)
{
	FILE* fp;
	
	if (fileName == NULL && abortOnError)
		ERRORABORT(FILE_OPENING_ERROR, "File name not given.");
	
	if (fileName == NULL)
		return NULL;
	
	fp = fopen(fileName, "r");
	return fp;
}

FILE *file_openrw(char* fileName, BOOL abortOnError)
{
	FILE* fp;
	
	if (fileName == NULL && abortOnError)
		ERRORABORT(FILE_OPENING_ERROR, "File name not given.");
	
	if (fileName == NULL)
		return NULL;
	
	fp = fopen(fileName, "w+");
	 return fp;
}

/*
 * Function Name: fileNextChar(FILE* fp)
47
 * Description:   Reads the file and returns next character, if file is null or its end of file, returns \�.
Celine Mercier committed
48 49 50 51 52 53 54 55 56 57 58 59 60 61
 */
char file_nextChar(FILE* fp)
{
	if (fp == NULL)
		return '\0';
	
	if(feof(fp))
		return '\0';
	
	return (char) fgetc(fp);
}

/*
 * Function Name: *fileNextLine(FILE *fp, char *buffer, int32_t bufferSize)
62
 * Description:   Reads the file and returns next line, if file is null or its end of file, returns \�.
Celine Mercier committed
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
 */
char *file_nextLine(FILE *fp, char *buffer, int32_t bufferSize)
{
	if(fp == NULL)
		return NULL;

	if(feof(fp))
		return NULL;

	return fgets(buffer, bufferSize, fp);
}


void exitIfEmptyFile(FILE *file)
{
    long savedOffset = ftell(file);
79 80 81 82 83
    if (fseek(file, 0, SEEK_END) != 0)
    {
        fprintf(stderr, "\nError moving the offset in an input file\n");
        exit(1);
    }
Celine Mercier committed
84 85 86 87 88 89 90 91 92

    if (ftell(file) == 0)
    {
        fprintf(stderr, "\nInput file is empty.\n");
        exit(1);
    }
    fseek(file, savedOffset, SEEK_SET);
}