getLine in C Implementation
#include <stdio.h>
// this function will get a line from a FILE *
// returns the amount of chars read
// you should pass it an NULL char *
int getLine(char ** line, FILE * fp)
{
//if you allocated something to line it will return error code -1
if(*line != NULL) return -1;
int bufflen = 80;
char * buff = malloc(bufflen * sizeof(char));
int i = 0;
while(1)
{
if(i == bufflen - 1) // if buffer is full resize
{
char * tempbuff = malloc(2 * bufflen * sizeof(char)); // we create a larger buffer
strncpy(tempbuff, buff, bufflen); // we copy the old buffer to the temp
free(buff); // we free the old buffer
buff = tempbuff; // we save the pointer to the new buffer to buff
tempbuff = NULL; // this is to prevent accidentally deleting buff
bufflen = bufflen * 2; // we update the size of the buffer
}
char c = fgetc(fp); // gets a char from file descriptor
if(c == '\n' || c == EOF)
{
buff[i] = '\0'; // make buff a c string
break;
}
else if(c == '\b' && i > 0) i = i - 2; // if back space remove element from buffer
else buff[i] = c; // if any other char add it
i++;
}
// copy buff into line
*line = malloc((i + 1) * sizeof(char)); // allocate space for NULL char at the end
strncpy(*line, buff, i + 1); // copy buffer to line, since buff is a c str its true length is i+1
free(buff); // make sure that you free your buffer!
return i; // returns the size of the line read
}
int main()
{
char * line = NULL;
const int lineLen = getLine(&line, stdin);
printf("line read: %s\n length: %d\n", line, lineLen);
// make sure to free lines after using them
free(line);
return 0;
}