-2

Am trying to open a file(Myfile.txt) and concatenate each line to a single buffer, but am getting unexpected output. The problem is,my buffer is not getting updated with the last concatenated lines. Any thing missing in my code?

Myfile.txt (The file to open and read)

Good morning line-001:
Good morning line-002:
Good morning line-003:
Good morning line-004:
Good morning line-005:
.
.
.

Mycode.c

#include <stdio.h>
#include <string.h>

int main(int argc, const char * argv[])
{
   /* Define a temporary variable */
   char Mybuff[100]; // (i dont want to fix this size, any option?)
   char *line = NULL;
   size_t len=0;
   FILE *fp;
   fp =fopen("Myfile.txt","r");
   if(fp==NULL)
   {
        printf("the file couldn't exist\n");
        return;
   }
   while (getline(&line, &len, fp) != -1 )
   {
       //Any function to concatinate the strings, here the "line"
       strcat(Mybuff,line);
   }
   fclose(fp);
   printf("Mybuff is: [%s]\n", Mybuff);

   return 0;
}

Am expecting my output to be:

Mybuff is: [Good morning line-001:Good morning line-002:Good morning line-003:Good morning line-004:Good morning line-005:]

But, am getting segmentation fault(run time error) and a garbage value. Any think to do? thanks.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
kahsay.k
  • 61
  • 7
  • 1
    you are experiencing a buffer overflow, with a hardcoded limit of 100. Use pointers, *hint: realloc* – t0mm13b Apr 17 '16 at 10:42
  • @t0mm13b: Thank u for replay, but still the same problem! Added Mybuff = realloc(Mybuff, sizeof mybuff), ...can you help me out pls, iam new to C language . – kahsay.k Apr 17 '16 at 10:55
  • Read [this Cornell lecture notes](http://www.cs.cornell.edu/courses/cs2022/2011sp/lectures/lect04.pdf) first! Get the K&R book also. Start from there. – t0mm13b Apr 17 '16 at 10:59
  • 1
    K&R are to old to be used anymore. One should forget that ever existed. – Michi Apr 17 '16 at 11:14

1 Answers1

0

Specify MyBuff as a pointer, and use dynamic memory allocation.

#include <stdlib.h>    /*  for dynamic memory allocation functions */

char *MyBuff = calloc(1,1);    /* allocate one character, initialised to zero */
size_t length = 1;

while (getline(&line, &len, fp) != -1 )
{
     size_t newlength = length + strlen(line)
     char *temp = realloc(MyBuff, newlength);
     if (temp == NULL)
     {
          /*  Allocation failed.  Have a tantrum or take recovery action */
     }
     else
     {
          MyBuff = temp;
          length = newlength;
          strcat(MyBuff, temp);
     }
}

/*  Do whatever is needed with MyBuff */

free(MyBuff);

/*   Also, don't forget to release memory allocated by getline() */

The above will leave newlines in MyBuff for each line read by getline(). I'll leave removing those as an exercise.

Note: getline() is linux, not standard C. A function like fgets() is available in standard C for reading lines from a file, albeit it doesn't allocate memory like getline() does.

Peter
  • 35,646
  • 4
  • 32
  • 74