Home >Backend Development >C++ >How Can I Efficiently Access a Specific Line in a Text File Without Loading the Entire File into Memory?

How Can I Efficiently Access a Specific Line in a Text File Without Loading the Entire File into Memory?

DDD
DDDOriginal
2025-01-15 08:01:46737browse

How Can I Efficiently Access a Specific Line in a Text File Without Loading the Entire File into Memory?

Efficiently read specified lines of text files to avoid memory usage

This article introduces several ways to efficiently read specified lines of text files without loading the entire file into memory.

.NET 4.0 and above

.NET 4.0 and higher can use the skip line method:

<code>string line = File.ReadLines(FileName).Skip(14).Take(1).First();</code>

This method reads line 15 directly without loading the entire file into memory.

.NET 4.0 or below

Before .NET 4.0, you need to skip line by line:

<code>string GetLine(string fileName, int line)
{
   using (var sr = new StreamReader(fileName)) {
       for (int i = 1; i < line; i++)
          sr.ReadLine();
       return sr.ReadLine();
   }
}</code>

This method only reads the required rows, thus reducing memory consumption.

Notes

While the skip line approach avoids storing the entire file in memory, it may be less efficient for accessing lines near the end of the file. Furthermore, the file structure must allow line numbers to be determined precisely, without relying on line numbers that may vary.

The above is the detailed content of How Can I Efficiently Access a Specific Line in a Text File Without Loading the Entire File into Memory?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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