我已经阅读了一个大约 120k 字的文件,所以我尝试快速阅读。 看过:
int x = setvbuf(fp, (char *)NULL, _IOFBF, BSZ);
assert( x == 0 && fp != NULL );
选项,但它需要一秒钟以上(1 mb 文件) 所以现在我尝试了这个方法:
fopen_s (&pFile,DICT,"rb");
if (pFile==NULL) {fputs ("File error",stderr); exit (1);}
// obtain file size:
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);
// allocate memory to contain the whole file:
buffer = (char*) malloc (sizeof(char)*lSize);
// copy the file into the buffer:
result = fread (buffer,1,lSize,pFile);
我如何从这里继续? 缓冲区包含一个单词列表,我想尽快一个一个地获取它们 因为我正在用这些词构建多重映射。
谢谢!
最佳答案
您的代码本质上是在实现 mmap()
。
mmap()
的美妙之处在于它会在需要时将实际页面加载到内存中。如果您的应用按顺序读取它们的速度非常快,操作系统将尽可能快地映射页面。
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define handle_error(msg) \
{ perror(msg); exit(EXIT_FAILURE); }
int
main(void)
{
int fd = open("english-words.10", O_RDONLY);
if (fd == -1)
handle_error("open");
struct stat sb;
if (fstat(fd, &sb) == -1)
handle_error("fstat");
size_t lSize = sb.st_size;
char* buffer = mmap(NULL, lSize, PROT_READ, MAP_PRIVATE, fd, 0);
if (buffer == MAP_FAILED)
handle_error("mmap");
// insert your mapping to a map here
munmap(buffer, lSize);
return 0;
}
请注意,我还使用了 fstat()
而不是您的 fseek
/ftell
。
关于C++ - 我读取了整个文件(_这是一个由 2 个空格分隔的单词列表_),如何快速分别获取单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10574977/