Ravi Vyas
Ravi Vyas

Reputation: 137

How to replace multiple blank lines with a single line in C language

I want to squeeze multiple lines in a single line. I have tried to apply my own logic but there is something wrong.

 char *p;
                    linecount=0;
                    while (fgets(buffer, sizeof(buffer), file))
                    {

                    //it will print the user input with number
                    p=buffer;

                    if('\r' == *p ||'\n' == *p )
                    {

                        linecount++;
                       if(linecount>2 )
                        printf("\n");
                    }

                    else
                    {
                        linecount=0;
                             printf("\t %s", p);

                    }

For instance a file has lines like

a
b


c


d
e

then the output should be

a
b

c

d
e

Basically, I am devloping a code for cat -s command.

Upvotes: 0

Views: 461

Answers (2)

William Pursell
William Pursell

Reputation: 212288

Why are you using fgets? (And more importantly, why are you not handling lines that are larger than your buffer?) You only need to look at one character at a time:

#include <stdio.h>

int main(void) {
    int c;
    int count=0;
    while((c=getchar())!=EOF) {
        if(c=='\n'){
            if(++count>2)
              continue;
        } else {
            count=0;
        }
        putchar(c);
    }
    return 0;
}

Upvotes: 0

Matthew Carlson
Matthew Carlson

Reputation: 664

In your if block:

if(linecount>2 )
    printf("\n");

What you are doing is printing out the 3rd, 4th, ..Nth blank lines.

The first blank like will have linecount = 1

The second blank like will have linecount = 2

I would reverse that logic to have

if( linecount == 0 ){
    linecount++;
    printf("\n");
}

This way, you will only print out the first blank line in the list of newlines.

Upvotes: 2

Related Questions