title: Using fgets + dynamic memory allocation
body: <p>I have a homework problem that I need help with. I need to implement a function <code>char *getStrFromFile(FILE*);</code>. I just simply don't understand it. I have attempted to figure out the question.</p>
  
  <blockquote>
    <p>This function safely reads a complete line of unknown length from the
    open file pointed to by fpin. It returns a line that is at most CHUNKSZ-1
    characters longer than the minimum needed to hold the line.
    It initially allocates an array of DEFLEN characters to hold the string,
    and if this space is inadequate to hold the string, it will iteratively
    create a new string that is CHUNKSZ larger, copy the old string to it
    release the old string, and then read in more characters from the file,
    and continue this until the entire line of arbitrary length can be returned.</p>
    
    <p>RETURNS: NULL if no characters are left in fpin, otherwise:
    pointer to allocated array at most CHUNKSZ-1 characters longer than
    miminum necessary to hold an arbitrarily long line from file fpin</p>
  </blockquote>
  
  <pre><code> int main(int nargs, char *args[])
   {
      FILE *fpin;
      char *getStrFromFile(FILE*);
      if (nargs != 2)
      {
         fprintf(stderr, "USAGE: %s &lt;file&gt;\n", args[0]);
         exit(1);
      }
      fpin = fopen(args[1], "r");
      while(1)
      {
         char *ln;
         ln = getStrFromFile(fpin);
         if (!ln)
            break;
         printf("%s", ln);
         free(ln);
      }
      fclose(fpin);
      return(0);
   }
  </code></pre>
  
  <p>That is the main method I have to use. Here is what I know so far.</p>
  
  <pre><code>char *getStrFromFile(FILE *fpin)
  {
    char string[DEFLEN];
    if(fgets(string, CHUNKSZ, fpin) != NULL) {
      int l = lstr(string);
      if(string[l-1] = '\n') {
        return string;
      } else {
        int size = 1;
        int end = 0;
        while (string[l-1] != '\n') {
          size += CHUNSZ;
          char *s2 = (char*)malloc(sizeof(char)+size);
          for(i = 0+end; i &lt; lstr(string); i++) {
            s2[i] = string[i];
          }
          end += lstr(string);
          fgets(string, size + end, fpin);
          return s2;
  </code></pre>