65.9K
CodeProject 正在变化。 阅读更多。
Home

FileDiff 竞赛条目

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.33/5 (5投票s)

2009年8月12日

CPOL
viewsIcon

21377

downloadIcon

145

两个文件之间的文本差异。

引言

这是一个关于文件差异的竞赛条目。

Using the Code

这个应用程序非常基础。它使用 FileStream 对象来执行其任务。

ASCIIEncoding encode = new ASCIIEncoding();
FileStream fileA = File.OpenRead(args[0]); 
FileStream fileB = File.OpenRead(args[1]);

int b = 0;
int l = 0;

fileA.Position = 0;
fileB.Position = 0;

我们首先打开文件并将文件中的位置设置为 0var b 是上次读取的字节,而 var l 是更改字节的长度。

while (fileA.Position <= (fileA.Length - 1))
{
    b = fileA.ReadByte();

    if (fileB.Position <= (fileB.Length - 1))
    {
        if (b != fileB.ReadByte())
        {
            l = 1;

            while (fileB.Position <= (fileB.Length - 1) && 
                fileB.ReadByte() != b)
            l += 1;

            byte[] s = new byte[l];
            fileB.Seek(fileB.Position - l, 0);
            fileB.Read(s, 0, l);
 
            Console.WriteLine("FileDiff Pos:{0}, Len{1}, Str:{2}",
                              fileA.Position, 
                              l, 
                              encode.GetString(s));
        }
    }
}

fileA.Close();
fileB.Close(); 

这是主应用程序循环。如你所见,它逐字节地遍历文件。当两个字节不同时,它停止查找并在流 B 中扫描下一个与流 A 相同的字节。

关注点

这是一个用 C# 和 .NET v2 编写的竞赛条目,包含 73 行代码,包括空行/注释和格式化代码 + 定时器等。不包括开销、空行或注释的代码行数为 28 行。它使用 4,384K 内存(专用工作集),EXE 文件大小为 5.5k。

运行时间大约为 30 毫秒,输出是文件中的位置、Diff 的长度和文本表示。

© . All rights reserved.