user1784688
user1784688

Reputation: 1

Using fgets + dynamic memory allocation

I have a homework problem that I need help with. I need to implement a function char *getStrFromFile(FILE*);. I just simply don't understand it. I have attempted to figure out the question.

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.

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

 int main(int nargs, char *args[])
 {
    FILE *fpin;
    char *getStrFromFile(FILE*);
    if (nargs != 2)
    {
       fprintf(stderr, "USAGE: %s <file>\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);
 }

That is the main method I have to use. Here is what I know so far.

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 < lstr(string); i++) {
          s2[i] = string[i];
        }
        end += lstr(string);
        fgets(string, size + end, fpin);
        return s2;

Upvotes: 0

Views: 2877

Answers (1)

suraj_fale
suraj_fale

Reputation: 960

This is not correct.

if(string[l-1] = '\n')

it must be

if(string[l-1] == '\n')

Upvotes: 5

Related Questions