Home>

As the title suggests, I want to convert crlf contained in a string literal to lf, but there are extra line breaks.

void replace_crlf_to_lf (char * buf, size_t size)
{
        for (int n = 0;n<size -1;n ++) {
                if (* (buf + n) =='\ r') {
                        * (buf + n) ='\ n';
                        n + = 1;
                }
        }
}


I tried to make a function like the one above, but when I look through it, the line breaks are added by one line. For example, it looks like the following.

〇Before conversion
ABCDEFG
ABCDEFG
〇 After conversion
ABCDEFG
ABCDEFG


As for the format, I want to convert the line feed code at the end of each line without inserting a line break like before conversion. What should I do?
I'm sorry for the introductory question, but I would appreciate it if you could teach me.

c
  • Answer # 1

    You want to change what was CR + LF to LF, but you just replace CR with LF.
    With this, the result is LF + LF, and the line breaks twice.
    Is it like this?

    (Addition)
    It is better to change the replace_crlf_to_lf function from void type to size_t type and return the converted size.
    Is there a use for the caller?

    size_t replace_crlf_to_lf (char * buf, size_t size)/* Change from void type to size_t type * /
    {
        for (int n = 0;n<size -1;n ++) {
            if (memcmp (buf + n, "\ r \ n", 2) == 0) {
                (void) memmove (buf + n, buf + n + 1, size --n --1);
                size-;
            }
        }
        return size;/* Return the converted size * /
    }