逐字节反向文件读取

本文关键字:文件 读取 字节 | 更新日期: 2023-09-27 18:25:00

这是我的代码。

        string FileName = @"File.txt";    
        if (File.Exists(FileName))
        {
            FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fs);
            for (long i = fs.Length; i > 0; i--)
            {
                Console.Write(Convert.ToChar(br.Read()));
            }
        }
        else
        {

但它仍然给了我相同的输出。。它从开始到结束按正确的顺序读取文件。我想把它从最后读到第一。

问题已解决最终代码

string FileName = @"File.txt";
        if (File.Exists(FileName))
        {
            FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);
            int length = (int)fs.Length;
            BinaryReader br = new BinaryReader(fs);
            byte[] myArray = br.ReadBytes((int)fs.Length);
            for (long i = myArray.Length - 1; i > 0; i--)
            {
                Console.Write(Convert.ToChar(myArray[i]));
            }
            Console.WriteLine();
        }
        else
        {
            Console.WriteLine("File Not Exists");
        }

逐字节反向文件读取

根据文件的大小,以下解决方案将消耗大量内存,因为它将在内存中保存文件内容的两个副本。但它应该可以处理较小的文件(认为大小小于大约10MB),并且很容易理解:

// using System;
// using System.IO;
byte[] fileContents = File.ReadAllBytes(filePath);
Array.Reverse(fileContents);
… // process `fileContents` instead of an input file stream

p.S.:如果您想处理较大的文件(大小为许多MB的文件),则不应使用此解决方案,因为它可能会很快导致OutOfMemoryException S。我建议您将大小合理(例如,64 KB)的文件块读取到内存中(从文件末尾附近开始,通过执行查找,一直到文件开头),并逐一处理这些文件

您需要使用BinaryReader的不同Read方法(Read(byte[]buffer, int index, int length))来指定要读取的数据的起始索引和长度。

for(long i = fs.Length; i > 0; i--)
{
    byte[] buffer = new byte[1];
    br.Read(buffer, i, 1);
    Console.Write(Convert.ToChar(buffer[0]));
}

编辑:我的方法不好,如果你想使用Read(byte[], int, int)方法,你应该首先读取整个文件,然后反转数组,就像@Crowdoder在他的解决方案中提到的那样。

使用ReadBytes(fs.Length)获取字节数组,然后在数组上使用循环。

只需读取流中的所有字节,将其保存到字节列表中,然后按如下方式反转:

List<byte> data = new List<byte>();
for (int i = 0; i < br.BaseStream.Length; ++i)
  data.Add(br.ReadByte());
data.Reverse();

我在这里发布了一个反转文件的答案。

如果您需要在不消耗内存的情况下反转文件,这里有一个单独的答案。