bozhidarc
bozhidarc

Reputation: 854

How to fill an array from file stream dynamically in C

I'm trying to combine words from characters which i'm reading from a file. The problem is in the combining the characters. The way I'm doing it is the following:

char *charArr
 while( (readChar = fgetc(fp)) != EOF ){
 charArr[i] = readChar;
 i++;
}

Upvotes: 0

Views: 2087

Answers (1)

John Bode
John Bode

Reputation: 123488

First of all, you need to allocate some memory for your charArr buffer; as written, charArr doesn't initially point anywhere meaningful:

char *charArr = malloc(SOME_INITIAL_SIZE);

where SOME_INITIAL_SIZE is big enough to handle most cases. For those times when it isn't big enough, you'll have to extend the buffer using realloc(). This means you also have to keep track of the current size of the buffer:

size_t currentSize = 0;
size_t i = 0;
char *charArr = malloc(SOME_INITIAL_SIZE);
if (!charArr)
{
  /**
   * memory allocation failed: for this example we treat it as a fatal
   * error and bail completely
   */
  exit(0);
}

currentSize = SOME_INITIAL_SIZE;
while ((readchar = fgetc(fp)) != EOF)
{
  /**
   * Have we filled up the buffer?
   */
  if (i == currentSize)
  {
    /**
     * Yes.  Double the size of the buffer.
     */
    char *tmp = realloc(charArr, currentSize * 2);
    if (tmp)
    {
      charArr = tmp;
      currentSize *= 2;
    }
    else
    {
      /**
       * The realloc call failed; again, we treat this as a fatal error. 
       * Deallocate what memory we have already allocated and exit
       */ 
      free(charArr);
      exit(0);
    }
  }
  charArr[i++] = readchar;
}

Don't forget to add a 0 terminator if you're treating the array as a string.

EDIT

However, the bigger question is why you think you have to read the entire file's contents into memory before filtering the data? Why not filter as you go?

Upvotes: 2

Related Questions