tausif
tausif

Reputation: 712

I need to print line number along with the line content but I am getting line number and the content in 2 different lines

main() 
{
     FILE *fp;
     char c;
     int count=1;
     fp=fopen("D:\file.txt","r");
     printf("%d ",count);
     c = fgetc(fp);
     while(c!=EOF) 
     {
         if(c=='\n')
         {
              count++;
              printf("\n%d",count);
         }
         putchar(c);
         c=fgetc(fp);
     }
     fclose(fp);
}

Upvotes: 0

Views: 152

Answers (1)

nos
nos

Reputation: 229108

You are also printing the newline you just read from the file,

Change

if(c=='\n') {
 count++;
 printf("\n%d ",count);
}
putchar(c);

to

if(c=='\n') {
 count++;
 printf("\n%d",count);
} else {
  putchar(c);
}

Alternativly, don't print the newline when you print the line number,

putchar(c);
if(c=='\n') {
  count++;
  printf("%d ",count);
}

You also have to change

char c;

to

int c;

getchar() returns an int, and EOF is a value that cannot be represented by a char.

Upvotes: 2

Related Questions