当拿到这个题目时,由于对文件的一些操作不是很熟悉,脑子感到一片混乱。在一番考虑之后,决定用c#完成,大概分为4个主要类,分别执行-c,-w,-l,-o操作。但当真正做起来的时候,也是查阅资料后,看了一些例子,为了简单起见,只编写了一个Wc类,在这个类中编写几个方法就可以完成这些操作。
在这个Wc类中,编写有以下方法
Check(List
StatisticsData(string tFile)//统计.c文件的信息
对传入的文件进行字符,行数,单词数的统计,详细过程见代码
public void Output()//输出结果
遍历操作符数组,识别用户需要执行什么操作,最后输出结果。不管操作符的顺序如何,都需要按顺序输出。
Write(string path)//文件的写入操作
执行文件的写入操作
public class Wc
{
private string tFile; // 文件名
private string oFile; //输出文件名
private List<string> arrParameter; // 参数集合
private int Charcount; // 字符数
private int Wordcount; // 单词数
private int Linecount; // 总行数
public void Check(List<string> arrParameter, string tFile)//检测输入
{
this.arrParameter = arrParameter;
this.tFile = tFile;
foreach (string s in arrParameter)
{
if (s != "-c" && s != "-w" && s != "-l" && s != "-o")
{
Console.WriteLine("操作 {0} 不存在", s);
}
else
{
//break;
}
}
}
public void StatisticsData(string tFile)//统计.c文件的信息
{
try
{
int nChar;
int charcount = 0;
int wordcount = 0;
int linecount = 0;
char[] symbol = { ‘ ‘, ‘,‘ };//由空格或逗号分割开的都视为单词,且不做单词的有效性校验
//文件打开操作
FileStream file = new FileStream(tFile, FileMode.Open, FileAccess.Read, FileShare.Read);
StreamReader sr = new StreamReader(file);
while ((nChar = sr.Read()) != -1)
{
charcount++; // 统计字符数
foreach (char c in symbol)
{
if (nChar == (int)c)
{
wordcount++; // 统计单词数
}
}
if (nChar == ‘\n‘)
{
linecount++; // 统计行数
}
}
Charcount = charcount;
Wordcount = wordcount + 1;
Linecount = linecount + 1;
sr.Close();
}
catch (IOException ex)
{
Console.WriteLine("输入格式错误");
return;
}
}
public void Output()//输出结果,根据操作,输出结果
{
bool isC = false;
bool isW = false;
bool isL = false;
foreach (string s in arrParameter)
{
if (s == "-c")
{
isC = true;
}
else if (s == "-w")
{
isW = true;
}
else if (s == "-l")
{
isL = true;
}
}
//如果同时涉及多项统计,如同时需要统计字符、单词和行数,
//则按照字符-- > 单词-- > 行数的顺序,依次分行显示。
//显示顺序与输入参数的次序无关
if (isC)
{
Console.WriteLine("{0},字 符 数:{1}", tFile, Charcount);
}
if (isW)
{
Console.WriteLine("{0},单 词 数:{1}", tFile, Wordcount);
}
if (isL)
{
Console.WriteLine("{0},总行数:{1}", tFile, Linecount);
}
Console.WriteLine();
}
public void Write(string path)//文件的写入操作
{
FileStream fs = new FileStream(path, FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
//开始写入
bool isC = false;
bool isW = false;
bool isL = false;
foreach (string s in arrParameter)
{
if (s == "-c")
{
isC = true;
}
else if (s == "-w")
{
isW = true;
}
else if (s == "-l")
{
isL = true;
}
}
if (isC)
{
sw.Write("{0},字 符 数:{1}\r\n", tFile, Charcount);
}
if (isW)
{
sw.Write("{0},单 词 数:{1}\r\n", tFile, Wordcount);
}
if (isL)
{
sw.Write("{0},总行数:{1}\r\n", tFile, Linecount);
}
Console.WriteLine("已写入文件:{0}", path);
Console.WriteLine("");
//清空缓冲区
sw.Flush();
//关闭流
sw.Close();
fs.Close();
}
}
在项目的bin\Debug文件中,用test.c文件测试-c,-w,-l操作,用result.txt做写入文件操作,所设计的测试用例基本满足用户日常操作
原文:https://www.cnblogs.com/ZY98/p/9692176.html