Home > Software design >  Problem with removing the "\n" from a string read in with getline()
Problem with removing the "\n" from a string read in with getline()

Time:11-14

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 ;).

CodePudding user response:

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 != -1 && 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';
    }

CodePudding user response:

To replace a potential '\n' in a string with a '\0':

 line[strcspn(line, "\n")] = '\0';

To utilizing the prior length chars_read:

 if (chars_read > 0 && line[chars_read - 1] == '\n') {
   line[--chars_read] = '\0';
 }
   
 

malloc() is 1 too short for OP's need.

    // char *line_rev = malloc(sizeof(char)*chars_read);
    char *line_rev = malloc(sizeof(char)*(chars_read   1));
    bar(line, line_rev, chars_read);
    if (strcmp(line, line_rev) == 0) {
  • Related