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

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

问题描述

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

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

推荐答案

严重迟到的如果您使用的是 .NET 4.0 或更高版本

File 类有一个新的 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 对于小文件可能会更快,但对于大文件会慢得多;尽管唯一的判断方法是使用秒表或代码分析器对其进行测量.

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天全站免登陆