tags:

views:

227

answers:

1

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++;
}
+2  A: 

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?

John Bode
This is off the main point, but you should exit with EXIT_FAILURE or some other *non-zero* return code for those failure cases.
Robert
The main idea of the program I want to write is to read a C file and count every letter in all identifiers in it.So I made two arrays, one with all operators (I called them word terminators) and ws and etc., and one with all C keywords.My idea was to read the file char by char (which i'm putting in array) until one of word terminator occurs. When that happens I'm comparing the word in array with the keywords, and if it's not a keyword I'm getting it's chars count.
bozhidarc