用c#实现文件的读取和系列操作

Gitee代码链接:https://gitee.com/hyr5201314/workcount

1.解题思路

  首先要先读取文件,然后调用函数实现返回文件的字符数,行数,单词总数。用的是c#来做。

 主要实现的功能:

wc.exe -c Mrhu.txt  //返回文件 Mrhu.txt 的字符数

wc.exe -w Mrhu.txt  //返回文件 Mrhu.txt 的单词总数

wc.exe -l Mrhu.txt  //返回文件 Mrhu.txt 的总行数

2,主要代码说明

读取文件

static void Main(string[] args)
{
string message = "";
while (message != "exit")
{
Console.Write("wc.exe ");
message = Console.ReadLine();
string[] arrMessSplit = message.Split(' ');
int Length = arrMessSplit.Length;
string[] sParameter = new string[Length - 1];
for (int i = 0; i < Length - 1; i++)
{
sParameter[i] = arrMessSplit[i];
}
// 获取文件名
string sFilename = arrMessSplit[Length - 1];
WC wc = new WC();
wc.Operator(sParameter, sFilename);
wc.BaseCount(sFilename);
wc.Display();
wc.SaveResult();

}

统计行数,字符数,单词数

public void BaseCount(string filename)
{
try
{
// 打开文件
FileStream file = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
StreamReader sr = new StreamReader(file);
int nChar;
int charcount = 0;
int wordcount = 0;
int linecount = 0;
//定义一个字符数组
char[] symbol = { ' ', '\t', ',', '.', '?', '!', ':', ';', '\'', '\"', '\n', '{', '}', '(', ')', '+' ,'-',
'*', '='};

while ((nChar = sr.Read()) != -1)
{
charcount++; // 统计字符数

foreach (char c in symbol)
{
if (nChar == (int)c)
{
wordcount++; // 统计单词数
}
}
if (nChar == '\n')
{
linecount++; // 统计行数
}
}
iCharcount = charcount;
iWordcount = wordcount + 1;
iLinecount = linecount + 1;
sr.Close();
}
catch (IOException ex)
{
Console.WriteLine(ex.Message);
return;
}

}

输出

public void SaveResult()
{
StreamWriter f = new StreamWriter(@"result.txt", false);
foreach (string a in sParameter)
{
if (a == "-c")
f.WriteLine("{0}字符数:{1}", sFilename, iCharcount);
if (a == "-w")
f.WriteLine("{0}单词数:{1}", sFilename, iWordcount);
if (a == "-l")
f.WriteLine("{0}行数:{1}", sFilename, iLinecount);
}
f.Close();
Console.ReadKey();
}
public void Display()
{
foreach (string s in sParameter)
{
if (s == "-c")
{
Console.WriteLine("字 符 数:{0}", iCharcount);
}
else if (s == "-w")
{
Console.WriteLine("单 词 数:{0}", iWordcount);
}
else if (s == "-l")
{
Console.WriteLine("总 行 数:{0}", iLinecount);
}
}
Console.WriteLine();

}

3.测试

5.参考文献

https://social.msdn.microsoft.com/Forums/en-US/8a720549-0791-45ba-ab78-ca211ac959f5/streamreaderread?forum=visualcshartzhchs

 

posted @ 2018-09-24 21:55  胡帅帅  阅读(414)  评论(0编辑  收藏  举报