"file" function for C

ma * file(const char * filename);

Header file:

  1. #ifndef FILE_H_
  2. #define FILE_H_
  3.  
  4. #define MAXCHAR 65535
  5.  
  6. /* matrix array data type "ma" */
  7. typedef struct {
  8.         char text[MAXCHAR];
  9. } ma;
  10.  
  11. ma * file(const char * filename);
  12.  
  13. #endif

Library code:

  1. /********************************************************************
  2.  * Name: file.c
  3.  * Author: Rashaud Teague
  4.  * Date: 07/01/2009
  5.  * License: GNU LGPL
  6.  * Description: File handling functions for C
  7.  ********************************************************************/
  8.  
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12.  
  13. #include "file.h"
  14.  
  15. /**
  16.  * name: file
  17.  * Reads the contents of a file into an array (data type "ma" see file.h)
  18.  * @param filename
  19.  * @return lines
  20.  */
  21. ma * file(const char * filename) {
  22.         /* set up FILE pointer */
  23.         FILE *pFile;
  24.         pFile = fopen(filename, "r");
  25.         if (pFile == NULL) exit(EXIT_FAILURE);
  26.        
  27.         /* line count */
  28.         int lc = 0;
  29.         static ma *lines;
  30.        
  31.         /* free any memory that has already been allocated then allocate memory */
  32.         if (lines != NULL) free(lines);
  33.         lines = (ma *) calloc(1, sizeof(ma));
  34.         if (lines == NULL) exit(EXIT_FAILURE);
  35.        
  36.         /* set memory reallocation variable for lines */
  37.         ma *new_lines;
  38.        
  39.         /* populate lines */
  40.         while (!feof(pFile)) {
  41.                 fgets(lines[lc].text, MAXCHAR, pFile);
  42.                 new_lines = realloc(lines, (lc+2) * sizeof(ma));
  43.                 if (new_lines == NULL) break;
  44.                 lines = new_lines;
  45.                 lc++;
  46.         }
  47.         /* close file */
  48.         fclose(pFile);
  49.        
  50.         /* set line_count to hold in a for loop external to this function */
  51.         extern int line_count;
  52.         line_count = lc+1;
  53.        
  54.         return lines;
  55. }

The test in main.c:

  1. /********************************************************************
  2.  * Name: main.c
  3.  * Author: Rashaud
  4.  * Date: <date>
  5.  * License: <license>
  6.  * Description: Test program for file.c functions
  7.  ********************************************************************/
  8.  
  9. #include <stdio.h>
  10.  
  11. #include "file.h"
  12.  
  13. int main(void) {
  14.         printf("\tTest\n\n");
  15.        
  16.         ma *lines = file("test.txt");
  17.        
  18.         int i;
  19.         for (i = 0; i < line_count; i++) {
  20.                 printf("%s", lines[i].text);
  21.         }
  22.        
  23.         return 0;
  24. }