确定的文本文件中的行数 [英] Determine the number of lines within a text file

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

问题描述

有没有一种简单的方法以编程方式确定一个文本文件中的行数?

Is there an easy way to programmatically determine the number of lines within a text file?

推荐答案

认真迟来编辑:如果您使用.NET 4.0或更高版本

文件类有一个新的 readlines方法 方法,它懒洋洋地列举了线,而不是贪婪地阅读它们都变成像 ReadAllLines 。所以,现在你可以有效率和简洁搭配:

The File class has a new ReadLines method which lazily enumerates lines rather than greedily reading them all into an array like ReadAllLines. So now you can have both efficiency and conciseness with:

var lineCount = File.ReadLines(@"C:\file.txt").Count();


原来的答案

如果你不是太费心约效率,可以简单的写:

If you're not too bothered about efficiency, you can simply write:

var lineCount = File.ReadAllLines(@"C:\file.txt").Length;

有关更有效的方法,你可以这样做:

For a more efficient method you could do:

var lineCount = 0;
using (var reader = File.OpenText(@"C:\file.txt"))
{
    while (reader.ReadLine() != null)
    {
        lineCount++;
    }
}

编辑:在回答关于效率问题

我说第二个是更有效的是对内存使用的原因,不一定速度。第一个加载该文件的全部内容到一个数组,这意味着它必须至少分配尽可能多的内存作为文件的大小。第二个循环仅一条线在时间,所以从来没有在一个时间分配的内存多行的价值。这是不适合小文件重要的,但为较大的文件可能是个问题(如果你试图找到在一个32位的系统上的4GB的文件的行数,例如,那里根本没有足够的用户模式地址空间分配给一个数组这个大)。

The reason I said the second was more efficient was regarding memory usage, not necessarily speed. The first one loads the entire contents of the file into an array which means it must allocate at least as much memory as the size of the file. The second merely loops one line at a time so it never has to allocate more than one line's worth of memory at a time. This isn't that important for small files, but for larger files it could be an issue (if you try and find the number of lines in a 4GB file on a 32-bit system, for example, where there simply isn't enough user-mode address space to allocate an array this large).

在速度方面我不认为会有很多吧。这可能是ReadAllLines有一些内部的优化,但在另一方面,它可能要分配的内存块巨大的。我猜ReadAllLines可能是小文件,但对于大文件速度慢显著快;但只有这样,才能知道是用秒表或code分析器来衡量它。

In terms of speed I wouldn't expect there to be a lot in it. It's possible that ReadAllLines has some internal optimisations, but on the other hand it may have to allocate a massive chunk of memory. I'd guess that ReadAllLines might be faster for small files, but significantly slower for large files; though the only way to tell would be to measure it with a Stopwatch or code profiler.

这篇关于确定的文本文件中的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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