template <class T>
class single_instance {
public:
static inline T instance() {
static T obj;
return obj;
}
private:
single_instance() = default;
virtual ~single_instance() = default;
};
#include <string.h>
#include <string>
#include "single_instance.hpp"
class string_utility {
public:
void replace_all(std::string &origin_str, const char *pattern, const char *val) {
size_t size = strlen(val);
std::string::size_type pos = 0;
while (pos != std::string::npos) {
pos = origin_str.find(pattern, pos);
if (std::string::npos == pos) {
break;
}
origin_str.replace(pos, size, val);
pos += size;
}
}
};
#define G_STRING_UTILITY single_instance<string_utility>::instance()
#pragma once
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include "string_utility.hpp"
class file_utility {
public:
bool sed_file(const char *file_path, const char *pattern, const char *val) {
struct stat st = { 0 };
if (lstat(file_path, &st) < 0) {
return false;
}
int fd = open(file_path, O_RDWR);
if (fd < 0) {
return false;
}
size_t file_size = st.st_size;
char *mmap_ptr = (char *)mmap(nullptr, file_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if ((nullptr == mmap_ptr ) || ((char *)-1 == mmap_ptr)) {
close(fd);
return false;
}
std::string str(mmap_ptr, file_size);
G_STRING_UTILITY.replace_all(str, pattern, val);
memcpy(mmap_ptr, str.c_str(), str.size());
munmap(mmap_ptr, file_size);
close(fd);
return true;
}
};
#define G_FILE_UTILITY single_instance<file_utility>::instance()
#include "file_utility.hpp"
int main() {
G_FILE_UTILITY.sed_file("./11.txt", "ABCD", "90000000000");
return 0;
}
g++ -std=c++11 -g -o Test test.cpp -I ./