This repository has been archived by the owner on Aug 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
/
readfile.cs
126 lines (108 loc) · 3.91 KB
/
readfile.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
/*
* Read the contents of a file; optionally limit to X number of lines from the beginning of the file or Y number of lines from the end
*
* USAGE: read.exe [+X] [-Y] <path_to_file>
*/
// To Compile:
// C:\Windows\Microsoft.NET\Framework\v2.0.50727\csc.exe /t:exe /out:readfile.exe readfile.cs
using System;
using System.IO;
class ReadFile
{
private static void PrintUsage()
{
string[] exePath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName.Split('\\');
string exeName = exePath[exePath.Length - 1];
Console.WriteLine(@"Read the contents of a file; optionally limit to X number of lines from the beginning of the file or Y number of lines from the end
USAGE:
{0} [+X] [-Y] <path_to_file>", exeName);
}
public static void Main(string[] args)
{
try
{
if (args.Length == 0)
{
PrintUsage();
return;
}
int head = 0;
int tail = 0;
string filePath = "";
int lineCount = 0;
// Parse arguments
for (int i = 0; i < args.Length; i++)
{
string arg = args[i];
if (arg.StartsWith("+"))
{
arg = arg.Replace("+", "");
bool test = int.TryParse(arg, out head);
if (test == false)
{
throw new ArgumentException("Invalid number of lines to read from head of file");
}
}
else if (arg.StartsWith("-"))
{
arg = arg.Replace("-", "");
bool test = int.TryParse(arg, out tail);
if (test == false)
{
throw new ArgumentException("Invalid number of lines to read from head of file");
}
}
else
{
filePath = arg;
}
}
if (File.Exists(filePath))
{
// If tail is specified, determine line count
if (tail > 0)
{
using (StreamReader file = new StreamReader(filePath))
{
while (file.ReadLine() != null)
{
lineCount++;
}
}
}
// Use StreamReader so the entire files doesn't have to get read into memory at once
using (StreamReader file = new StreamReader(filePath))
{
int i = 0;
string line;
while ((line = file.ReadLine()) != null)
{
// Print the line if it's less than head, greater than tail, or neither head nor tail are specified
if ((head > 0 && i < head) || (tail > 0 && i >= lineCount - tail) || (head == 0 && tail == 0))
{
Console.WriteLine(line);
}
// Stop when head is reached if tail is not also specified (for efficiency)
if (head > 0 && i == head && tail == 0)
{
break;
}
i++;
}
}
}
else
{
throw new Exception("File does not exist");
}
}
catch (Exception e)
{
Console.Error.WriteLine("[-] ERROR: {0}", e.Message.Trim());
}
finally
{
Console.WriteLine("\nDONE");
}
}
}