3
\$\begingroup\$

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!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ I don't see the need for this. 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\$ Commented Nov 1, 2020 at 18:12
  • 1
    \$\begingroup\$ Do note that getline isn't a standard C function and you should probably tag the question accordingly. \$\endgroup\$ Commented Nov 2, 2020 at 6:43

1 Answer 1

6
\$\begingroup\$

This function can be written like this:

char* readStdinLine()
{
        char*  buffer  = NULL;
        size_t bufsize = 0;
        ssize_t characters = getline(&buffer, &bufsize, stdin);
        if (characters == -1) {
            free(buffer);
            buffer = NULL;
        }
        else if (buffer[characters-1] == '\n') {
            buffer[characters-1] = '\0';
        }
        return buffer;
}

The getline() function does everything you need. You simply need to check for errors and remove the new line character)

\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.