ma * file(const char * filename);
Header file:
#ifndef FILE_H_
#define FILE_H_
#define MAXCHAR 65535
/* matrix array data type "ma" */
typedef struct {
char text[MAXCHAR];
} ma;
ma * file(const char * filename);
#endif
Library code:
/********************************************************************
* Name: file.c
* Author: Rashaud Teague
* Date: 07/01/2009
* License: GNU LGPL
* Description: File handling functions for C
********************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "file.h"
/**
* name: file
* Reads the contents of a file into an array (data type "ma" see file.h)
* @param filename
* @return lines
*/
ma * file(const char * filename) {
/* set up FILE pointer */
FILE *pFile;
pFile = fopen(filename, "r");
if (pFile == NULL) exit(EXIT_FAILURE);
/* line count */
int lc = 0;
static ma *lines;
/* free any memory that has already been allocated then allocate memory */
if (lines != NULL) free(lines);
lines = (ma *) calloc(1, sizeof(ma));
if (lines == NULL) exit(EXIT_FAILURE);
/* set memory reallocation variable for lines */
ma *new_lines;
/* populate lines */
while (!feof(pFile)) {
fgets(lines[lc].text, MAXCHAR, pFile);
new_lines = realloc(lines, (lc+2) * sizeof(ma));
if (new_lines == NULL) break;
lines = new_lines;
lc++;
}
/* close file */
fclose(pFile);
/* set line_count to hold in a for loop external to this function */
extern int line_count;
line_count = lc+1;
return lines;
}
The test in main.c:
/********************************************************************
* Name: main.c
* Author: Rashaud
* Date: <date>
* License: <license>
* Description: Test program for file.c functions
********************************************************************/
#include <stdio.h>
#include "file.h"
int main(void) {
ma *lines = file("test.txt");
int i;
for (i = 0; i < line_count; i++) {
}
return 0;
}