Home > Backend Development > C++ > How to Efficiently Count Lines in a Text File?

How to Efficiently Count Lines in a Text File?

DDD
Release: 2025-01-11 09:48:41
Original
918 people have browsed it

How to Efficiently Count Lines in a Text File?

Text file line count counting method

Counting the number of lines in a text file is a common task in programming. Here are a few efficient methods:

1. Use File.ReadAllLines():

If efficiency is not a major issue, this method is concise and clear:

<code class="language-csharp">var lineCount = File.ReadAllLines(@"C:\file.txt").Length;</code>
Copy after login

While convenient, this method loads the entire file into memory, which can cause performance issues for large files.

2. Use StreamReader:

To improve efficiency, especially when processing large files, it is recommended to use StreamReader:

<code class="language-csharp">var lineCount = 0;
using (var reader = File.OpenText(@"C:\file.txt"))
{
    while (reader.ReadLine() != null)
    {
        lineCount++;
    }
}</code>
Copy after login

This method iterates row by row to avoid memory consumption issues.

Memory usage and efficiency:

It's worth noting that while the first approach is convenient, it consumes more memory by storing the entire file in an array. The second method uses less memory but may not be efficient for smaller files.

Conclusion:

The choice of method depends on the specific requirements of the task. The first method is a quick solution for small files where memory usage is not an issue. For large files, the second method is more efficient in terms of memory consumption.

The above is the detailed content of How to Efficiently Count Lines in a Text File?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template