Created
March 11, 2013 15:09
-
-
Save iwillspeak/5134902 to your computer and use it in GitHub Desktop.
C++ Program to find a string in a file. Use `strfind file text` to search for <text> in <file>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
compile it with
$ clang strfind.cpp -ostrfind