ch8_03.cs

来自「《c#技术内幕代码》」· CS 代码 · 共 86 行

CS
86
字号
using System;
using System.IO;

class CH8_3
{
   public static void ShowFile( string name )
   {
      try
      {
         FileStream fs = new FileStream( name, FileMode.Open );
         BinaryReader sr = new BinaryReader( fs );

	 int nPos = 0;      
	 Boolean bHeader = false;
	 int nChar = -1;
	 int[] nLine = new int[16];
	 int nLinePos = 0;
	 
	 do
	 {
	    nChar = sr.Read();
	    if ( nChar != -1 )
	    {
	       // See if we are at a line break.
	       if ( bHeader == false )
	       {
	          // If we have any characters, dump them in ascii if possible
		  if ( nLinePos > 0 )
		  {
		     for ( int i=0; i<16; ++i )
		        if ( nLine[i] >= ' ' && nLine[i] < 'z' )
			   Console.Write("{0}", nLine[i].ToChar());
			else
			   Console.Write(".");
		  }
	          Console.Write("\n{0}: ", nPos.Format("X5", null) );
		  bHeader = true;
		  nLinePos = 0;
	       }
	       
               Console.Write("{0} ", nChar.Format("X2", null) );
	       nLine[nLinePos] = nChar;
	       nPos ++;
	       nLinePos ++;
	       // See if the next position is a line break
	       if ( nPos % 15 == 0 )
	          bHeader = false;
	    }
         } while ( nChar != -1 );
	 
         // Fill in the line
	 for ( int i=nPos; i%15 != 0; ++i )
	    Console.Write("   ");
	 
         // If we have any characters, dump them in ascii if possible
         if ( nLinePos > 0 )
         {
            for ( int i=0; i<nPos%15; ++i )
               if ( nLine[i] >= ' ' && nLine[i] < 'z' )
        	   Console.Write("{0}", nLine[i].ToChar());
	       else
	       	   Console.Write(".");
	 }
	 
      }
      catch ( Exception e )
      {
         Console.WriteLine("Exception in ShowFile: {0}", e );
      }
   }
   
   public static void Main(string[] args)
   {
      if ( args.Length < 1 )
      {
         Console.WriteLine("Usage: Ch8_2 text-file-name");
	 return;
      }

      Console.WriteLine("Dumping file {0}:", args[0] );      
      ShowFile( args[0] );
   }
}


⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?