为什么 StreamReader.EndOfStream 属性更改 BaseStream.Position 值

发布于 2024-12-07 11:28:49 字数 1211 浏览 0 评论 0原文

我编写了这个小程序,它从 Random.txt 中读取每 5 个字符 在 random.txt 中,我有一行文本:ABCDEFGHIJKLMNOPRST。我得到了预期的结果:

  • A 的位置是 0
  • F 的位置是 5
  • K 的位置是 10
  • P 的位置是 15

这是代码:

static void Main(string[] args)
{
    StreamReader fp;
    int n;
    fp = new StreamReader("d:\\RANDOM.txt");
    long previousBSposition = fp.BaseStream.Position;
    //In this point BaseStream.Position is 0, as expected
    n = 0;

    while (!fp.EndOfStream)
    {
        //After !fp.EndOfStream were executed, BaseStream.Position is changed to 19,
        //so I have to reset it to a previous position :S
        fp.BaseStream.Seek(previousBSposition, SeekOrigin.Begin);
        Console.WriteLine("Position of " + Convert.ToChar(fp.Read()) + " is " + fp.BaseStream.Position);
        n = n + 5;
        fp.DiscardBufferedData();
        fp.BaseStream.Seek(n, SeekOrigin.Begin);
        previousBSposition = fp.BaseStream.Position;
    }
}

我的问题是,为什么在 while (!fp.EndOfStream) BaseStream.Position 更改为 19,例如 BaseStream 的末尾。我预计,当我调用 EndOfStream 检查时,BaseStream.Position 将保持不变,这显然是错误的?

谢谢。

I wrote this small program which reads every 5th character from Random.txt
In random.txt I have one line of text: ABCDEFGHIJKLMNOPRST. I got the expected result:

  • Position of A is 0
  • Position of F is 5
  • Position of K is 10
  • Position of P is 15

Here is the code:

static void Main(string[] args)
{
    StreamReader fp;
    int n;
    fp = new StreamReader("d:\\RANDOM.txt");
    long previousBSposition = fp.BaseStream.Position;
    //In this point BaseStream.Position is 0, as expected
    n = 0;

    while (!fp.EndOfStream)
    {
        //After !fp.EndOfStream were executed, BaseStream.Position is changed to 19,
        //so I have to reset it to a previous position :S
        fp.BaseStream.Seek(previousBSposition, SeekOrigin.Begin);
        Console.WriteLine("Position of " + Convert.ToChar(fp.Read()) + " is " + fp.BaseStream.Position);
        n = n + 5;
        fp.DiscardBufferedData();
        fp.BaseStream.Seek(n, SeekOrigin.Begin);
        previousBSposition = fp.BaseStream.Position;
    }
}

My question is, why after line while (!fp.EndOfStream) BaseStream.Position is changed to 19, e.g. end of a BaseStream. I expected, obviously wrong, that BaseStream.Position will stay the same when I call EndOfStream check?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

烏雲後面有陽光 2024-12-14 11:28:49

确定 Stream 是否位于其末尾的唯一方法是实际从中读取内容并检查返回值是否为 0。(StreamReader 还有另一种方法 -检查其内部缓冲区,但您正确地不要通过调用 DiscardBufferedData 来让它执行此操作。)

因此,EndOfStream 必须从基本流中读取至少一个字节。由于逐字节读取效率低下,因此会读取更多内容。这就是为什么调用 EndOfStream 会将位置更改为末尾(对于较大的文件来说,它不会是文件末尾)。

看来您实际上并不需要使用 StreamReader,因此您应该直接使用 Stream (或具体地说 FileStream):(

using (Stream fp = new FileStream(@"d:\RANDOM.txt", FileMode.Open))
{
    int n = 0;

    while (true)
    {
        int read = fp.ReadByte();
        if (read == -1)
            break;

        char c = (char)read;
        Console.WriteLine("Position of {0}  is {1}.", c, fp.Position);
        n += 5;
        fp.Position = n;
    }
}

我不是确定在这种情况下设置超出文件末尾的位置会做什么,您可能需要为此添加检查。)

Thre only certain way to find out whether a Stream is at its end is to actually read something from it and check whether the return value is 0. (StreamReader has another way – checking its internal buffer, but you correctly don't let it do that by calling DiscardBufferedData.)

So, EndOfStream has to read at least one byte from the base stream. And since reading byte by byte is inefficient, it reads more. That's the reason why the call to EndOfStream changes the position to the end (it woulnd't be the end of file for bigger files).

It seems you don't actually need to use StreamReader, so you should use Stream (or specifically FileStream) directly:

using (Stream fp = new FileStream(@"d:\RANDOM.txt", FileMode.Open))
{
    int n = 0;

    while (true)
    {
        int read = fp.ReadByte();
        if (read == -1)
            break;

        char c = (char)read;
        Console.WriteLine("Position of {0}  is {1}.", c, fp.Position);
        n += 5;
        fp.Position = n;
    }
}

(I'm not sure what does setting the position beyond the end of file do in this situation, you may need to add a check for that.)

同展鸳鸯锦 2024-12-14 11:28:49

基本流的 Position 属性指的是 缓冲区 中最后读取的字节的位置,而不是 StreamReader 光标的实际位置。

The base stream's Position property refers to the position of the last read byte in the buffer, not the actual position of the StreamReader's cursor.

凡尘雨 2024-12-14 11:28:49

你是对的,无论如何,根据 (MSDN :从文件中读取文本) 使用 StreamReader 读取文本文件的正确方法如下,而不是您的(这也总是通过使用 using 块来关闭和处置流):

try
{
    // Create an instance of StreamReader to read from a file.
    // The using statement also closes the StreamReader.
    using (StreamReader sr = new StreamReader("TestFile.txt"))
    {
        String line;
        // Read and display lines from the file until the end of
        // the file is reached.
        while ((line = sr.ReadLine()) != null)
        {
            Console.WriteLine(line);
        }
    }
}
catch (Exception e)
{
    // Let the user know what went wrong.
    Console.WriteLine("The file could not be read:");
    Console.WriteLine(e.Message);
}

You are right and I could reproduce your issue as well, anyway according to (MSDN: Read Text from a File) the proper way to read a text file with a StreamReader is the following, not yours (this also always closes and disposes the stream by using a using block):

try
{
    // Create an instance of StreamReader to read from a file.
    // The using statement also closes the StreamReader.
    using (StreamReader sr = new StreamReader("TestFile.txt"))
    {
        String line;
        // Read and display lines from the file until the end of
        // the file is reached.
        while ((line = sr.ReadLine()) != null)
        {
            Console.WriteLine(line);
        }
    }
}
catch (Exception e)
{
    // Let the user know what went wrong.
    Console.WriteLine("The file could not be read:");
    Console.WriteLine(e.Message);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文