Home >Backend Development >C++ >How Can I Efficiently Read Specific Lines from a Large Text File Without Using String Arrays?

How Can I Efficiently Read Specific Lines from a Large Text File Without Using String Arrays?

Susan Sarandon
Susan SarandonOriginal
2025-01-15 09:21:50940browse

How Can I Efficiently Read Specific Lines from a Large Text File Without Using String Arrays?

Line-wise selective reading of large text files

Question:

How to read and store specific lines from a large text file without using a string array?

Background:

The text file provided has a structured format: the first 25 lines contain the information, followed by a variable number of lines (the number is determined by the value of line 17). The goal is to extract and store the first 25 rows from the file as independent values ​​and store subsequent rows as an array.

Solution:

.NET 4.0 Method:

If using .NET 4.0 or higher, ReadLines methods can access rows directly. To read line 15:

<code class="language-csharp">string line = File.ReadLines(FileName).Skip(14).Take(1).First();</code>

General method:

For earlier .NET versions or if sequential reading of lines cannot be avoided:

<code class="language-csharp">string GetLine(string fileName, int line)
{
   using (var sr = new StreamReader(fileName))
   {
       for (int i = 1; i <= line; i++)
       {
           if (sr.ReadLine() == null) return null; // 处理文件结尾
           if (i == line) return sr.ReadLine();
       }
       return null;
   }
}</code>

This method reads all lines before the target line.

Note:

Normally it cannot be assumed that the first n lines can be deleted without re-reading and re-writing the file. However, the solution provided here does not require rows to be deleted.

The above is the detailed content of How Can I Efficiently Read Specific Lines from a Large Text File Without Using String Arrays?. 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