简体   繁体   English

C ++快速读取较大文件的最佳方法

[英]C++ Best way to quickly read from larger file

During runtime I frequently need to read small portions of larger file (300 mb). 在运行期间,我经常需要读取较大文件的一小部分(300 mb)。 Currently I always open up the file, read from it and then close it again like that: 目前我总是打开文件,从中读取然后再次关闭它:

FILE *file =fopen(szFileName,"rb");
if (file)
{
    fseek( file,iFirstByteToRead, SEEK_SET);
    fread(nEncodedBytes,sizeof(unsigned char), iLenCompressedBytes, file);
    fclose(file);
}

But that is too slow because I do that so frequently. 但这太慢了,因为我经常这样做。 Also I am not sure if fread could be sped up. 另外我不确定fread是否可以加速。

What is the best practice for such a situation, please? 请问这种情况的最佳做法是什么?

Keep the file open and you'll do much better. 保持文件打开,你会做得更好。

Try mmap for improved performance still. 尝试使用mmap来提高性能。

The work related to file control always causes expensive cost. 与文件控制相关的工作总是会导致昂贵的成本。 If you control several times for manage the file, you don't have to close file pointer. 如果您多次控制以管理文件,则不必关闭文件指针。

Like below, once you get the file pointer, 如下所示,一旦你得到文件指针,

FILE *stream = fopen(stream, “rb”);

if (stream != NULL)

You have to close stream file pointer after finishing in your program, and also if you have to manage a number of files, you would use a thread, which is dedicated as a file reading. 您必须在程序结束后关闭流文件指针,并且如果您必须管理许多文件,您将使用专用作文件读取的线程。

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

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