Replacing multiple new lines in a file with just one

后端 未结 5 2057
轻奢々
轻奢々 2021-01-22 12:00

This function is supposed to search through a text file for the new line character. When it finds the newline character, it increments the newLine counter, and when

5条回答
  •  死守一世寂寞
    2021-01-22 12:54

    What the sample code resolved is:

    1) squeeze the consecutive a few '\n' to just one '\n'

    2) Get rid the leading '\n' at the beginning if there is any.

      input:   '\n\n\naa\nbb\n\ncc' 
      output:   aa'\n'    
                bb'\n' //notice, there is no blank line here
                cc
    

    If it was the aim, then your code logic is correct for it.

    • By defining newLine = 1 , it will get rid of any leading '\n' of the input txt.

    • And when there is a remained '\n' after processing, it will output a new line to give a hint.

    Back to the question itself, if the actual aim is to squeeze consecutive blank lines to just one blank line(which needs two consecutive '\n', one for terminate previous line, one for blank line).

    1) Let's confirm the input and expected output firstly,

    Input text:

    aaa'\n' //1st line, there is a '\n' append to 'aaa'  
    '\n'    //2nd line, blank line
    bbb'\n' //3rd line, there is a '\n' append to 'bbb'
    '\n'    //4th line, blank line
    '\n'    //5th line, blank line
    '\n'    //6th line, blank line
    ccc     //7th line,
    

    Expected Output text:

    aaa'\n' //1st line, there is a '\n' append to 'aaa'  
    '\n'    //2nd line, blank line
    bbb'\n' //3rd line, there is a '\n' append to 'bbb'
    '\n'    //4th line, blank line
    ccc     //5th line,
    

    2) If it is the exact program target as above,then

    if (c == '\n')
    {
        newLine++;
        if (newLine < 3) // here should be 3 to print '\n' twice,
                         // one for 'aaa\n', one for blank line 
        {
            //printf("new line");
            putchar(c); 
        }
    }
    

    3) If you have to process the Windows format file(with \r\n ending) under Cygwin, then you could do as follows

    while ((c = fgetc(fileContents)) != EOF)
    {   
        if ( c == '\r') continue;// add this line to discard possible '\r'
        if (c == '\n')
        {
            newLine++;
            if (newLine < 3) //here should be 3 to print '\n' twice
            {
                printf("new line");
                putchar(c); 
            }
        }
        else 
        {
            putchar(c); 
            newLine = 0;
        }
    }
    

提交回复
热议问题