簡體   English   中英

用C ++快速讀取文件中的特定單詞

[英]Read a particular word from a file in C++ quickly

我的經理告訴我要創建一個測試,我需要測試一個特定的單詞是否存在於文件中。 問題是文件可能非常大並且如果測試運行了很長時間,那么在回歸測試期間它將失敗。 所以我想知道標准C ++中是否有任何便利API用於我的目的,它會很快告訴我這個詞是否存在。 我不想知道這個詞的位置。 這個詞是在文件開頭附近的某個地方,但它的確切位置是未知的。 在這方面有什么幫助嗎? 謝謝。

如果文件沒有特定的結構,除了包含單詞(按任何順序),唯一的解決方案是線性搜索,這意味着讀取整個文件。 如果您知道該單詞只能在開頭附近,那么您只需要搜索到可以找到該單詞的最遠點。

如果這還不夠快,你要么必須以某種方式構造文件(排序等),要么你必須加快閱讀程序本身(例如使用mmap )。

mmap文件,然后strnstr它可能是最好的。 除非你對文件的結構有所了解,否則會限制你必須搜索的區域。

extern "C" {
#include <sys/mman.h>
#include <fcntl.h>
}

#include <cstring>
#include <cerrno>
#include <iostream>

int main(int argc, char* argv[]) {

    // I don't check the arguments here, you should probably do that

    // String to search for
    char* search_string = argv[2];

    // Open the file so we can map it
    int fd = open(argv[1], O_RDONLY);
    if (fd < 0) {
        std::cout << "Open failed: " << strerror(errno) << std::endl;
        return 1;
    }

    // Find the length of the file so we know how much to map
    off_t len = lseek(fd, 0, SEEK_END);
    if (len == -1) {
        std::cout << "Seek failed: " << strerror(errno) << std::endl;
        return 1;
    }

    // map the file into memory
    char* file_contents = (char*)mmap(
        NULL, len, PROT_READ, MAP_FILE | MAP_PRIVATE, fd, 0);
    if (file_contents == MAP_FAILED) {
        std::cout << "map failed: " << strerror(errno) << std::endl;
        return 1;
    }

    // We don't need the file open any more, we do need to unmap it later though
    close(fd);

    // Search for the string in the file here
    char* found = strnstr(file_contents, search_string, len);
    if (found == NULL)
        std::cout << "String not found" << std::endl;
    else
        std::cout << "String found @ " << found - file_contents << std::endl;

    munmap(file_contents, len);
}

內存映射文件訪問允許您直接訪問文件的某些部分而無需將其加載到內存中。

據我所知,Qt提供了內存映射,而且,C ++標准庫也沒有。

您還可以使用操作系統的本機API。 適用於UNIX的mmap ,適用於Windows的CreateFileMapping

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM