您可以使用mmap
将整个文件映射到内存中,然后进行strnstr
搜索:
#include <sys/mman.h>
const char *fileName = "~/test.txt";
long fileLength;
// open file and get it's length
FILE *fptr = fopen(fileName, "r");
if (fptr == NULL || ferror(fptr))
{
perror("could not open file");
fclose(fptr);
return 0;
}
fseek(fptr, 0, SEEK_END);
fileLength = ftell(fptr);
// return to the start of the file
fseek(fptr, 0, SEEK_SET);
// map the file
char *fileData = mmap(NULL, fileLength, PROT_READ, MAP_FILE | MAP_SHARED, fileno(fptr), 0);
if (fileData == MAP_FAILED)
perror("could not map file");
// scan the file
char stringToSearchFor[] = "this is my string!";
if (strnstr(fileData, stringToSearchFor, fileLength) != NULL)
{
printf("file contains the string!");
}
else {
printf("file doesn't contain the string");
}
// clean up our code
munmap(fileData, fileLength);
fclose(fptr);