移动文件光标行? [英] Moving the file cursor up lines?

查看:137
本文介绍了移动文件光标行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我GOOGLE了这个像疯了似的,而我似乎无法找到任何引用在所有这种特殊类型的问题。

I've googled this like crazy, and I can't seem to find any reference at all to this particular type of problem.

我有一个的StreamReader 对象有文件,我想读超过一定数量行的文件,在一定的次数,但是,似乎没有任何办法来移动文件光标文件中的某些位置。

I have a StreamReader object with a file, and I want to read over a certain number of lines in the file a certain number of times, however, There doesn't seem to be any way to move the file cursor to certain positions in the file.

(无代码,因为我不知道我将如何去写这样的事情)

(No code because I have no clue how I would go about writing something like this)

推荐答案

您应该能够使用

myStreamReader.BaseStream.Position = desiredPosition;
myStreamReader.DiscardBufferedData();



到流移动到特定的地方。

to move the stream to a specific place.

编辑:接下来的问题是如何找到 desiredPosition 。既然你想通过文件移动位置的的,不是的转发的,它遵循您已经阅读在一些点的每个位置。你需要跟踪你所在的流中,当你阅读你的线条,并在名单,LT店位置; INT>位置。最初,该列表应包含 0 在零位。如在处理线,添加行的长度加换行符的大小的列表。当你想回去行 K 位置[K] 应该有你需要的位置。

The next question is how to find the desiredPosition. Since you want to move the position back through the file, not forward, it follows that you have read each position at some point. You need to keep track of where you are in the stream as you read your lines, and store positions in a List<int> positions. Initially, the list should contain 0 at position zero. As you process lines, add the length of the line plus the size of line break to the list. When you want to go back to line k, positions[k] should have the position you need.

例如,如果你的文件有下面几行,你的编码使用每个字母一个字符,并在文件中的行分隔符是Windows风格的 \ r\\\

For example, if your file has the lines below, your encoding uses one character per letter, and the line separator in the file is Windows-style \r\n

Quick
brown fox
jumps over lazy
dog

那么你的位置列表应该有 {0,7,17,34} 请注意,我在每行的分隔符加2。

then your positions list should have {0, 7, 17, 34} Note that I added 2 on each line for the separator characters.

PS这是一个丑陋的解决方案,是不是?如果它是任何安慰,你是不是谁跑进去的第一人。 这是从别人谁想要一个有点猥亵的咆哮解决类似的问题早在2007年。

P.S. This is an ugly solution, isn't it? If it is any comfort, you are not the first person who ran into it. Here is a somewhat obscene rant from someone who wanted to solve a similar problem back in 2007.

这篇关于移动文件光标行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆