2014-02-24 47 views
1

我有一个程序来读取百万行文件。每行有一个浮点值。该值将被读入并放入数组中的一个元素中。StreamReader不会停止读取文本文件

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并重新开始。

此代码或多或少基于微软在其网站上推荐的内容......关于我在做什么错误的任何想法?

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

1 million line file- OneDrive

回答

4

你不应该有forwhile。你只需要一个循环:

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。

+0

这两个代码块实际上做了稍微不同的事情。第一个不会停留在第1000000条,但第二个是。 – Dirk

+0

@Dirk我假定文件正好有1000000个条目,所以在1000000th之后'ReadLine'将返回'null'。但是,他们有些不同。 – MarcinJuraszek

+0

* Ed McMahon声音* 您是正确的先生! 这是漫长的一天。我一直试图在语言之间转换相同的算法。我想那是从我身边飞过来的。谢谢。 – nerdenator

1

我在我的手机上,所以我为简洁而道歉。你的外部while循环将会触发你的100万行中的每一行,而你的内部for循环将迭代100万次,总共有1万亿次迭代。此外,你的while条件可以利用file.EndOfStream属性。

1

基本上,你正在转换每一行1000000次,因为你的while循环中有for循环读取。

只需删除for循环,并取代它与我++

每次file.ReadLine把它叫做读取文件中的一行,直到它到达文件的末尾,成为空(为此退出你的while-循环)。