S
somenath
Hi All,
I was trying to write a function which will read one line from a
specified file and return the line. It is currently working fine.
But it would be very much helpful for me if some one point out some
improvement points or some error in the code.
Regards,
Somenath
char* get_line(FILE *fp)
{
int len = 2; /*First memory is allocated for 2 bytes 1 for one
character another for '\0'*/
int pos = 0;
char *buff;
char *temp_buff;
char c;
buff = malloc(len);
if (fp == NULL || buff == NULL)
{
return (NULL);
}
while ( (c = fgetc(fp)) != EOF)
{
buff[pos++] = c;
if (c == '\n')
{
/*pos is decremented by one because, currently buff[pos]
contains newline at the
position of pos
but we need to put newline at the end od buf[pos] ;So
pos is decremented by one and
at the end before
return we are assignning '\0' at the place of newline i.e
'\n' is replcaed by '\0'.*/
pos = pos-1;
/*We reached the end of the line*/
break;
}
if (pos == len)
{
len += 2;
temp_buff = realloc(buff,len);
if (temp_buff == NULL)
{
/*Reallocation of memory fails */
return NULL;
}
else
{
buff = temp_buff;
}
}
}
buff[pos] = '\0';
return buff = (c==EOF?NULL:buff);
}
I was trying to write a function which will read one line from a
specified file and return the line. It is currently working fine.
But it would be very much helpful for me if some one point out some
improvement points or some error in the code.
Regards,
Somenath
char* get_line(FILE *fp)
{
int len = 2; /*First memory is allocated for 2 bytes 1 for one
character another for '\0'*/
int pos = 0;
char *buff;
char *temp_buff;
char c;
buff = malloc(len);
if (fp == NULL || buff == NULL)
{
return (NULL);
}
while ( (c = fgetc(fp)) != EOF)
{
buff[pos++] = c;
if (c == '\n')
{
/*pos is decremented by one because, currently buff[pos]
contains newline at the
position of pos
but we need to put newline at the end od buf[pos] ;So
pos is decremented by one and
at the end before
return we are assignning '\0' at the place of newline i.e
'\n' is replcaed by '\0'.*/
pos = pos-1;
/*We reached the end of the line*/
break;
}
if (pos == len)
{
len += 2;
temp_buff = realloc(buff,len);
if (temp_buff == NULL)
{
/*Reallocation of memory fails */
return NULL;
}
else
{
buff = temp_buff;
}
}
}
buff[pos] = '\0';
return buff = (c==EOF?NULL:buff);
}