I'd like to read a line from stdin, excluding the newline character. I've written the function:
/* read in a line from stdin, NULL on failure
* does not include trailing newline
*/
char*
readStdinLine() {
char* buffer;
size_t bufsize = 32;
size_t characters;
buffer = (char *) malloc(bufsize * sizeof(char));
if (buffer == NULL)
return NULL;
characters = getline(&buffer, &bufsize, stdin);
buffer[--characters] = '\0';
char* text = (char *) malloc(characters);
for (int i = 0; i < characters + 1; i++) {
text[i] = buffer[i];
}
free(buffer);
return text;
}
This seems inneficient, I'm essentially reading in the line twice, once in getline and once to remove the trailing newline. That doesn't seem like the most memory-efficient algorithm, and I would like to remove the newline without copying, if that is at all possible.
I'm very new to C (have used C++, Java, etc, but never a systems language without objects) so I would appreciate learning all the code style things I've done wrong as well. Thanks!
getline()
does all this automatically. If you want a version that removed the newline character then you simply remove it (if it exists (Note last line in a file may not have a new line)). \$\endgroup\$getline
isn't a standard C function and you should probably tag the question accordingly. \$\endgroup\$