Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
C++ Program to find a string in a file. Use `strfind file text` to search for <text> in <file>
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);
}
@iwillspeak

This comment has been minimized.

Copy link
Owner Author

@iwillspeak iwillspeak commented Mar 11, 2013

compile it with $ clang strfind.cpp -ostrfind

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment