simple - but it won't work;)

From: The Big Bad Wolf (woldra_at_softhome.net)
Date: 01/31/05


Date: Mon, 31 Jan 2005 14:08:21 GMT

Hi all,

I want to read a file line by line avoiding fgets() for I don't know how
long the lines gonna be. Maybe not very efficient but it should work,
shouldn't it?

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

void addchar(char* buf,char ch) {
   char* tmp;
   tmp = malloc(strlen(buf)+2);
   sprintf(tmp,"%s%c",buf,ch);
   buf=realloc(buf,strlen(tmp)+1);
   strcpy(buf,tmp);

   fprintf (stderr,"%c - %i/%i : %s\n",ch,strlen(buf),strlen(tmp),buf);
   free (tmp);
}

int main (int argc, char** argv) {
   FILE *file;
   char* buf;
   int c;
   buf=malloc(1);

   if ((file = fopen(argv[1],"r"))==NULL) {
     fprintf(stderr,"cant open file %s \n",argv[1]);
     exit (1);
   }

   while ((c=fgetc(file))!=EOF) {
     if (c!='\n') {
       addchar(buf,c);
     } else {
       printf("%s\n",buf);
       free(buf);
       buf=malloc(1);
     }
   }

   fclose(file);
   return (0);
}

it segfaults after 12 bytes???
can anybody please tell me what's wrong about it.

Cheers
Wolf



Relevant Pages