gpt4 book ai didi

c# - StreamReader 不会停止读取文本文件

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

我有一个程序可以读取一百万行的文件。每行都有一个浮点值。该值将被读入并放入数组中的一个元素中。

using System;
using System.Diagnostics;
using System.IO;

namespace sort1mRandFloat
{
public class Program
{
static void Main()
{
Console.WriteLine("Creating Single array...");
Single[] fltArray = new Single[1000000];

Console.WriteLine("Array created, making string...");
String line;
Console.WriteLine("String created, opening file...");
StreamReader file = new StreamReader(@"C:\\Users\\Aaron\\Desktop\\rand1mFloats.txt");
Console.WriteLine("File opened, creating stopwatch and starting main execution event. See you on the other side.");
int i;
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
while((line = file.ReadLine()) != null)
{
for(i=0; i < 1000000; i++)
{
fltArray[i] = Convert.ToSingle(line);
if (i == 999999)
Console.WriteLine("At 999999");
}
}

file.Close();
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
String elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds/10);
Console.WriteLine("It took " + elapsedTime + " to read a thousand lines into the array.\n");
Console.WriteLine("Element 0 is: " + fltArray[0]);
Console.WriteLine("Element 999999 is: " + fltArray[999999]);
Console.ReadLine();
}
}
}

当这段代码在文件上运行时,它永远不会停止。它正在寻找一些东西来告诉它它在磁贴的尽头或其他东西,但它没有找到。在填充第 999,999 个元素后,它循环回到 0 并重新开始。

此代码或多或少基于 Microsoft 在其网站上推荐的内容...知道我做错了什么吗?

可以在下面找到该文件。由于我还不能将文件存储在数组中,所以我不能说它需要多长时间才能工作。文件中有很多值。计量连接警告:18 MB 文件。

1 million line file- OneDrive

最佳答案

while 中不应该有 for。你只需要一个循环:

var i = 0;
while((line = file.ReadLine()) != null)
{
fltArray[i] = Convert.ToSingle(line);
if (i == 999999)
Console.WriteLine("At 999999");
i++;
}

或使用for:

for(i=0; i < 1000000 && (line = file.ReadLine()) != null; i++)
{
fltArray[i] = Convert.ToSingle(line);
if (i == 999999)
Console.WriteLine("At 999999");
}

更新

我得到了您的文件的以下结果:

Creating Single array...
Array created, making string...
String created, opening file...
File opened, creating stopwatch and starting main execution event. See you on the other side.
At 999999
It took 00:00:00.42 to read a thousand lines into the array.

Element 0 is: 0,9976465
Element 999999 is: 0,04730097

发布构建,在 VS 之外运行,i5-3317U @ 1.7GHz。

关于c# - StreamReader 不会停止读取文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21978820/

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