#include <sys/mman.h>
#include <sys/types.h>
#include <fcntl.h>
#include<string.h>
#include<stdio.h>
#include <unistd.h>
#include <sys/stat.h>
//求子串
char* substr(const char*str, unsigned long start, unsigned long end);
void replace(const char *ori, const char *dst, int fd, unsigned char *buffer, unsigned long size);
//替换文本. ori:将要替换的字符串、dst:替换的目的字符串, path:文件名
void replace(const char *ori, const char *dst, const char *path);
int main(int argc, char** argv) // map a normal file as shared mem:
{
replace("abc", "123456", "/Users/zctech/Desktop/test.cpp");
}
//求子串
char* substr(const char*str, unsigned long start, unsigned long end)
{
unsigned long n = end - start;
static char stbuf[1024 * 512];
strncpy(stbuf, str + start, n);
stbuf[n] = 0; //字串最后加上0
return stbuf;
}
void replace(const char *ori, const char *dst, int fd, unsign
c/c++ 修改文本文件内容、替换字符串函数(linux、mac下)【增强版】Windows版会陆续发布
本文档展示了如何在C/C++中使用内存映射在Linux和Mac系统下修改文本文件内容,替换特定字符串。通过`mmap`函数映射文件到内存,然后遍历内存查找并替换目标字符串,最后更新文件内容。提供的`replace`函数实现了这一功能,并附带了求子串的辅助函数。
摘要由CSDN通过智能技术生成