You need dynamic memory management, and use the fgets
function to read your line. However, there seems to be no way to see how many characters it read. So you use fgetc:
char * getline(void) {
char * line = malloc(100), * linep = line;
size_t lenmax = 100, len = lenmax;
int c;
if(line == NULL)
return NULL;
for(;;) {
c = fgetc(stdin);
if(c == EOF)
break;
if(--len == 0) {
len = lenmax;
char * linen = realloc(linep, lenmax *= 2);
if(linen == NULL) {
free(linep);
return NULL;
}
line = linen + (line - linep);
linep = linen;
}
if((*line++ = c) == '
')
break;
}
*line = '';
return linep;
}
Note: Never use gets ! It does not do bounds checking and can overflow your buffer
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…