c/c++ 修改文本文件内容、替换字符串函数(linux、mac下)【增强版】Windows版会陆续发布

本文档展示了如何在C/C++中使用内存映射在Linux和Mac系统下修改文本文件内容,替换特定字符串。通过`mmap`函数映射文件到内存,然后遍历内存查找并替换目标字符串,最后更新文件内容。提供的`replace`函数实现了这一功能,并附带了求子串的辅助函数。
摘要由CSDN通过智能技术生成
#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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值