欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#从文件或标准输入设备读取指定行的方法

程序员文章站 2023-11-06 21:10:04
本文实例讲述了c#从文件或标准输入设备读取指定行的方法。分享给大家供大家参考。具体如下: using system; using system.io; usi...

本文实例讲述了c#从文件或标准输入设备读取指定行的方法。分享给大家供大家参考。具体如下:

using system;
using system.io;
using system.runtime.interopservices;
using system.text.regularexpressions;
using system.collections.generic;
namespace robvanderwoude
{
 class readline
 {
  static int main( string[] args )
  {
   #region command line parsing
   string filename = string.empty;
   int linestart = 1;
   int lineend = 2;
   bool concat = false;
   bool addspaces = false;
   string concatchar = string.empty;
   bool skipempty = false;
   bool trimlines = false;
   bool numlines = false;
   bool redirected;
   bool set_c = false;
   bool set_l = false;
   bool set_s = false;
   bool set_t = false;
   bool set_input = false;
   if ( consoleex.inputredirected )
   {
    set_input = true;
    redirected = true;
   }
   else
   {
    if ( args.length == 0 )
    {
     return writeerror( );
    }
    redirected = false;
   }
   foreach ( string arg in args )
   {
    if ( arg[0] == '/' )
    {
     try
     {
      switch ( arg.toupper( )[1] )
      {
       case '?':
        return writeerror( );
       case 'c':
        if ( arg.toupper( ) != "/c" && arg.toupper( ) != "/cs" )
        {
         return writeerror( "invalid command line switch " + arg );
        }
        concat = true;
        if ( arg.toupper( ) == "/cs" )
        {
         addspaces = true;
        }
        if ( set_c )
        {
         return writeerror( "duplicate command line argument /c*" );
        }
        set_c = true;
        break;
       case 'l':
        if(arg.toupper( ).startswith( "/l:" ) && arg.length > 3)
        {
         if ( arg[2] == ':' )
         {
          string linessel = arg.substring( 3 );
          string pattern = @"^(\-?\d+)$";
          match match = regex.match( linessel, pattern );
          if ( match.success )
          {
           linestart = convert.toint32( match.groups[1].value );
           lineend = linestart + 1;
          }
          else
          {
           pattern = @"^(\-?\d+)\.\.(\-?\d+)$";
           match = regex.match( linessel, pattern );
           if ( match.success )
           {
            linestart = convert.toint32( match.groups[1].value );
            lineend = convert.toint32( match.groups[2].value ) + 1;
           }
           else
           {
            pattern = @"^(\-?\d+),(\-?\d+)$";
            match = regex.match( linessel, pattern );
            if ( match.success )
            {
             // numlines is true if the second number 
             //specifies the number of lines instead of a line number
             numlines = true;
             linestart = convert.toint32( match.groups[1].value );
             lineend = convert.toint32( match.groups[2].value );
             if ( lineend < 1 )
             {
              return writeerror( "invalid number of lines (" + lineend.tostring( ) + "), must be 1 or higher" );
             }
            }
           }
          }
         }
         else
         {
          return writeerror( "invalid command line switch " + arg );
         }
        }
        else
        {
         return writeerror( "invalid command line switch " + arg );
        }
        if ( set_l )
        {
         return writeerror( "duplicate command line argument /l" );
        }
        set_l = true;
        break;
       case 's':
        if ( arg.toupper( ) != "/se" )
        {
         return writeerror( "invalid command line switch " + arg );
        }
        skipempty = true;
        if ( set_s )
        {
         return writeerror( "duplicate command line argument /se" );
        }
        set_s = true;
        break;
       case 't':
        if ( arg.toupper( ) != "/t" )
        {
         return writeerror( "invalid command line switch " + arg );
        }
        trimlines = true;
        if ( set_t )
        {
         return writeerror( "duplicate command line argument /t" );
        }
        set_t = true;
        break;
       default:
        return writeerror( "invalid command line switch " + arg );
      }
     }
     catch
     {
      return writeerror( "invalid command line switch " + arg );
     }
    }
    else
    {
     if ( set_input )
     {
      return writeerror( "multiple inputs specified (file + redirection or multiple files)" );
     }
     if ( redirected )
     {
      return writeerror( "do not specify a file name when using redirected input" );
     }
     else
     {
      filename = arg;
     }
    }
   }
   #endregion
   try
   {
    int count = 0;
    bool output = false;
    string[] lines;
    list<string> alllines = new list<string>( );
    if ( redirected )
    {
     // read standard input and store the lines in a list
     int peek = 0;
     do
     {
      alllines.add( console.in.readline( ) );
     } while ( peek != -1 );
     // convert the list to an array
     lines = alllines.toarray( );
    }
    else
    {
     // read the file and store the lines in a list
     lines = file.readalllines( filename );
    }
    // check if negative numbers were used, and if so, 
    //calculate the resulting line numbers
    if ( linestart < 0 )
    {
     linestart += lines.length + 1;
    }
    if ( lineend < 0 )
    {
     lineend += lines.length + 1;
    }
    if ( numlines )
    {
     lineend += linestart;
    }
    // iterate through the array of lines and display 
    //the ones matching the command line switches
    foreach ( string line in lines )
    {
     string myline = line;
     if ( trimlines )
     {
      myline = myline.trim( );
     }
     bool skip = skipempty && ( myline.trim( ) == string.empty );
     if ( !skip )
     {
      count += 1;
      if ( count >= linestart && count < lineend )
      {
       if ( concat )
       {
        console.write( "{0}{1}", concatchar, myline );
       }
       else
       {
        console.writeline( myline );
       }
       if ( addspaces )
       {
        concatchar = " ";
       }
      }
     }
    }
   }
   catch ( exception e )
   {
    return writeerror( e.message );
   }
   return 0;
  }
  #region redirection detection
  public static class consoleex
  {
   public static bool outputredirected
   {
    get
    {
     return filetype.char != getfiletype( getstdhandle( stdhandle.stdout ) );
    }
   }
   public static bool inputredirected
   {
    get
    {
     return filetype.char != getfiletype( getstdhandle( stdhandle.stdin ) );
    }
   }
   public static bool errorredirected
   {
    get
    {
     return filetype.char != getfiletype( getstdhandle( stdhandle.stderr ) );
    }
   }
   // p/invoke:
   private enum filetype { unknown, disk, char, pipe };
   private enum stdhandle { stdin = -10, stdout = -11, stderr = -12 };
   [dllimport( "kernel32.dll" )]
   private static extern filetype getfiletype( intptr hdl );
   [dllimport( "kernel32.dll" )]
   private static extern intptr getstdhandle( stdhandle std );
  }
  #endregion
  #region error handling
  public static int writeerror( exception e = null )
  {
   return writeerror( e == null ? null : e.message );
  }
  public static int writeerror( string errormessage )
  {
   if ( string.isnullorempty( errormessage ) == false )
   {
    console.error.writeline( );
    console.foregroundcolor = consolecolor.red;
    console.error.write( "error: " );
    console.foregroundcolor = consolecolor.white;
    console.error.writeline( errormessage );
    console.resetcolor( );
   }
   console.error.writeline( );
   console.error.writeline( "readline, version 0.30 beta" );
   console.error.writeline( "return the specified line(s) from a file or standard input" );
   console.error.writeline( );
   console.error.write( "usage: " );
   console.foregroundcolor = consolecolor.white;
   console.error.writeline( "readline filename [ options ]" );
   console.resetcolor( );
   console.error.write( " or: " );
   console.foregroundcolor = consolecolor.white;
   console.error.writeline( "readline [ options ] < filename" );
   console.resetcolor( );
   console.error.write( " or: " );
   console.foregroundcolor = consolecolor.white;
   console.error.writeline( "command | readline [ options ]" );
   console.resetcolor( );
   console.error.writeline( );
   console.error.write( "where: " );
   console.foregroundcolor = consolecolor.white;
   console.error.write( "filename" );
   console.resetcolor( );
   console.error.writeline( " is the optional file to be read" );
   console.foregroundcolor = consolecolor.white;
   console.error.write( "   command" );
   console.resetcolor( );
   console.error.writeline( " is the optional command whose output is to be read" );
   console.error.writeline( );
   console.error.write( "options: " );
   console.foregroundcolor = consolecolor.white;
   console.error.write( "/c   c" );
   console.resetcolor( );
   console.error.writeline( "oncatenate lines" );
   console.foregroundcolor = consolecolor.white;
   console.error.write( " /cs  c" );
   console.resetcolor( );
   console.error.write( "oncatenate lines with " );
   console.foregroundcolor = consolecolor.white;
   console.error.write( "s" );
   console.resetcolor( );
   console.error.writeline( "paces in between" );
   console.foregroundcolor = consolecolor.white;
   console.error.write( " /l:n" );
   console.resetcolor( );
   console.error.write( " read line " );
   console.foregroundcolor = consolecolor.white;
   console.error.writeline( "n" );
   console.resetcolor( );
   console.foregroundcolor = consolecolor.white;
   console.error.write( " /l:n..m" );
   console.resetcolor( );
   console.error.write( " read lines " );
   console.foregroundcolor = consolecolor.white;
   console.error.write( "n" );
   console.resetcolor( );
   console.error.write( " through " );
   console.foregroundcolor = consolecolor.white;
   console.error.writeline( "m" );
   console.error.write( "   /l:n,m" );
   console.resetcolor( );
   console.error.write( "  read " );
   console.foregroundcolor = consolecolor.white;
   console.error.write( "m" );
   console.resetcolor( );
   console.error.write( " lines starting at line " );
   console.foregroundcolor = consolecolor.white;
   console.error.writeline( "n" );
   console.resetcolor( );
   console.error.writeline( "(negative numbers start counting from the end backwards)" );
   console.foregroundcolor = consolecolor.white;
   console.error.write( "   /se  s" );
   console.resetcolor( );
   console.error.write( "kip " );
   console.foregroundcolor = consolecolor.white;
   console.error.write( "e" );
   console.resetcolor( );
   console.error.writeline( "mpty lines" );
   console.foregroundcolor = consolecolor.white;
   console.error.write( "   /t   t" );
   console.resetcolor( );
   console.error.writeline( "rim leading and trailing whitespace from lines" );
   console.error.writeline( );
   console.error.writeline( "examples:" );
   console.error.writeline( "readline file read the first non-empty line (default)" );
   console.error.writeline( "readline file /l:2 /se read the second non-empty line of file" );
   console.error.writeline( "readline file /l:5..7 read lines 5..7 of file" );
   console.error.writeline( "readline file /l:-1 read the last line of file" );
   console.error.writeline( "readline file /l:-2..-1 read the last 2 lines of file" );
   console.error.writeline( "readline file /l:-2,2 read the last 2 lines of file" );
   console.error.writeline( );
   console.error.write( "check for redirection by hans passant on " );
   console.foregroundcolor = consolecolor.darkgray;
   console.error.writeline( "*.com" );
   console.error.writeline( "/questions/3453220/how-to-detect-if-console-in-stdin-has-been-redirected" );
   console.resetcolor( );
   console.error.writeline( );
   console.error.writeline( "written by rob van der woude" );
   return 1;
  }
  #endregion
 }
}

希望本文所述对大家的c#程序设计有所帮助。