gpt4 book ai didi

C#阅读流

转载 作者:太空宇宙 更新时间:2023-11-03 19:14:19 25 4
gpt4 key购买 nike

我想用 C# 读取一个 .txt 文件,但我不会同时读取所有行。例如,考虑 500 行文本文件。我想要一个函数运行 25 次并且每次读取 20 个连续的行。函数第一次调用时,会读取1到20行,第二次调用时,会读取21-40行。

下面的简单代码在 C++ 中执行此操作,但我不知道如何在 C# 中实现它:

string readLines(ifstream& i)
{
string totalLine="", line = "";
for(int i = 0; i < 20; i++){
getline(i, line);

totalLine += line;
}
return totalLine;
}

int main()
{

// ...
ifstream in;
in.open(filename.c_str());
while(true){
string next20 = readLines(in);
// so something with 20 lines.
}
// ...

}

最佳答案

这里有多种选择,但一种简单的方法是:

using (var reader = File.OpenText("file.txt"))
{
for (int i = 0; i < 25; i++)
{
HandleLines(reader);
}
}

...

private void HandleLines(TextReader reader)
{
for (int i = 0; i < 20; i++)
{
string line = reader.ReadLine();
if (line != null) // Handle the file ending early
{
// Process the line
}
}
}

关于C#阅读流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18233824/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com