Search code examples
cstringpointersiowindows-subsystem-for-linux

Problem with removing the "\n" from a string read in with getline()


Hello I am very new to the C programming language and I am writing my first program in C. I want to remove the "\n" from the end of a line read in with getline() and replace it with "\0". I tried it with the code that is in the if-statement, the first expression in my while loop but I am not getting the behaviour I intended. I tried the solution suggested here Function to remove newline has no effect? but it did not work for my case, and I don't understand why, I assume I am making a mistake with the pointers but I can not figure out what it is. What exactly am I doing wrong and how can I fix it?

void foo(FILE *input, FILE *output) {
    char *line = NULL;
    size_t length = 0;
    ssize_t chars_read;

    while ((chars_read= getline(&line, &length, input)) != -1) {
        if (line[chars_read-1] == '\n') {
            line[chars_read-1] = '\0';
            chars_read = chars_read - 1;
        }
        char *line_rev = malloc(sizeof(char)*chars_read);
        bar(line, line_rev, chars_read);
        if (strcmp(line, line_rev) == 0) {
            ...
        } else {
            ...
        }
        free(line_rev);
    }

    free(line);
}

Update: Thanks for all the helpful answers! For future visitors: Be careful when working on WSL, new lines might be '\n' or '\r' depending on the OS you are working on. For details check Ted's answer ;).


Solution

  • What you need is simply to put a \0 where the \n is.

    It could look like this;

    char *line = NULL;
    size_t length = 0;
    ssize_t chars_read;
    // ...
    
        if(chars_read > 0 && line[chars_read-1] == '\n') {
            line[chars_read-1] = '\0';
            // special care for windows line endings:
            if(chars_read > 1 && line[char_read-2] == '\r') line[chars_read-2] = '\0';
        }