I'm pretty new to C, so as part of my learning I want to make a function that simply returns a string which is the next line in the input without any arguments needed.
This is what I have so far:
#define BUFFER 256
char *str;
char *getline()
{
if (str == 0)
str = (char*)calloc(BUFFER, sizeof(char));
if (fgets(str, BUFFER, stdin) != 0)
{
size_t len = strlen(str);
if (len > 0 && str[len-1] == '\n')
str[len-1] = '\0';
return str;
}
return 0;
}
Now, is this the best way to do such thing? Is there a better way you can thing of?
If it is the best way, where should I free what I've allocated with calloc
?