Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New line character in c#

Tags:

c#

newline

I wrote this code to count the number of characters in a text file :

sr.BaseStream.Position = 0;
sr.DiscardBufferedData();
int Ccount = 0;
while (sr.Peek() != -1)
{
  sr.Read();
  Ccount++;
}

but after applying this code to a file contains :

1
2
3
4
5
6
7
8
9
0

Ccount = 30 ???? why? I am using Windows Xp on virtual box on my Macbook the program used : Microsoft Visual Basic 2010.

like image 581
Ammar Alyousfi Avatar asked Apr 15 '13 13:04

Ammar Alyousfi


2 Answers

In Windows each new line consists of two characters \r and \n. You have 10 lines, each line have 1 visible characters and 2 new line characters which add up to 30 characters.

If you have created your file in Mac or Unix/Linux you would have gotton different result (20 characters). Because Unix uses only \n and Mac uses only \r for a new line.

You can use some editors (such as Notepad++) to show you new line characters, or even switch between different modes (DOS/Unix/Mac).

like image 198
Sina Iravanian Avatar answered Sep 21 '22 13:09

Sina Iravanian


You're reading one character at a time, and each line contains three characters:

  • one digit
  • one carriage return (\r)
  • one newline (\n)

(Windows uses \r\n as its newline sequence. The fact that you're running in a VM on a Mac doesn't affect that.)

like image 27
RichieHindle Avatar answered Sep 21 '22 13:09

RichieHindle