Created
October 2, 2017 19:31
-
-
Save Jacajack/08c9e88541eed0fe91b07d9cc3c68780 to your computer and use it in GitHub Desktop.
File queuing service (rev. 1)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include "fload.h" | |
#define MAX_FILE_COUNT 256 | |
static FILE *files[MAX_FILE_COUNT] = {0}; | |
static int fcount = 0; | |
//Queues specific file for loading | |
int floadQueue( const char *fname ) | |
{ | |
if ( fname == NULL ) return 1; //Check the file name | |
if ( fcount >= MAX_FILE_COUNT ) return 1; //Check for file stack overflow | |
if ( ( files[fcount] = fopen( fname, "rt" ) ) == NULL ) return 1; //Attempt to open the file | |
fcount++; //Update stack counter | |
return 0; | |
} | |
//Reads single line from file queue (returned string must be freed by user) | |
char *floadRead( ) | |
{ | |
const int buflen = 4096; | |
char *buf = NULL; | |
FILE *f = NULL; | |
if ( fcount <= 0 ) return NULL; //Check file count (recursion lock) | |
if ( ( buf = calloc( buflen, sizeof( char ) ) ) == NULL ) return NULL; //Allocate memory for the new line | |
f = files[fcount - 1]; | |
//Check if another line can be read | |
if ( fgets( buf, buflen, f ) == NULL ) | |
{ | |
//If not, attempt to read from another file | |
free( buf ); | |
fclose( f ); | |
fcount--; | |
return floadRead( ); | |
} | |
return buf; | |
} | |
//Skip reading current file | |
void floadSkip( ) | |
{ | |
FILE *f = files[fcount - 1]; | |
if ( fcount <= 0 ) return; | |
fclose( f ); | |
fcount--; | |
} | |
//Close all queued files | |
void floadEnd( ) | |
{ | |
while ( fcount ) | |
fclose( files[--fcount] ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment