简体   繁体   English

如何直接在 C 中获取文本文件上的特定行? (无需逐行迭代)

[英]How to get a specific line on a text file directly in C? (without iterating line-by-line)

Is there a way to get a specific line inside a text file without iterating line-by-line in C?有没有办法在不逐行迭代 C 的情况下获取文本文件中的特定行?

for example I have this text file names.txt it contains the following names below;例如,我有这个文本文件names.txt它包含以下名称;

John
James
Julia
Jasmine

and I want to access 'Julia' right away without iterating through 'John' and 'James'?, Something like, just give the index value of '2' or '3' to access 'Julia' right away.并且我想立即访问 'Julia' 而无需遍历 'John' 和 'James'?,例如,只需给出索引值 '2' 或 '3' 即可立即访问 'Julia'。

Is there a way to do this in C?有没有办法在 C 中做到这一点?

I just want to know how because I want to deal with a very large text file something like in about 3 billion lines and I want to access a specific line in there right away and iterating line-by-line is very slow我只是想知道如何处理,因为我想处理一个非常大的文本文件,比如大约 30 亿行,我想立即访问其中的特定行并且逐行迭代非常慢

You have to at least once iterate thru all lines.您必须至少遍历所有行。 In this iteration, before reading a line, you record the position in the file and save it to an array or to another file (Usually named an index file).在此迭代中,在读取一行之前,您将 position 记录在文件中,并将其保存到数组或另一个文件(通常称为索引文件)中。 The file shall have a fixed record size that is good for storing the position off the line in the text file.该文件应具有固定的记录大小,有利于在文本文件中离线存储 position。

Later, when you want to access a give line, you either use the array to get the position (Line number is the array index) or the file (You seek into the file to offset line number of record size) and read the position.稍后,当您想要访问给定行时,您可以使用数组获取 position(行号是数组索引)或文件(您在文件中查找以偏移记录大小的行号)并读取 position。 Once you get the position, you can see into the text file to that position and read the line.获得 position 后,您可以查看该 position 的文本文件并阅读该行。

Each time the text file is updated, you must reconstruct the array or index file.每次更新文本文件时,都必须重建数组或索引文件。

There are other way to do that, but you need to better explain the context.还有其他方法可以做到这一点,但您需要更好地解释上下文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM