替换文本中的字符串02

*实现替换文件中指定的内容
----Created by cryking----
--------2012.02.12--------*/
#include<iostream>
#include<fstream>
#include<string.h>
#include<stdlib.h>
#include<windows.h>
using namespace std;

char *strstr_rep(char *source, const char *old, const char *ne)//字符替换
{
char *org = source;
char temp[1000];
int old_length = strlen(old);//获得将被替换的字符串的大小
int i, j, k, location = -1;
for (i = 0; source[i] && (location == -1); ++i)//location查找将被替换的字符串的位置
for (j = i, k = 0; source[j] == old[k]; j++, k++)
if (!old[k + 1])
location = i;
if (location != -1)//开始替换
{
for (j = 0; j < location; j++)//先把被替换的字符串的前一部分COPY到temp
temp[j] = source[j];
for (i = 0; ne[i]; i++, j++)//再把替换的新字符串COPY到temp
temp[j] = ne[i];
for (k = location + old_length; source[k]; k++, j++)//把剩下的内容COPY到temp
temp[j] = source[k];
temp[j] = NULL;
for (i = 0; source[i] = temp[i]; i++); //把临时字符串temp复制给source
}
return org;
}
int main()
{
system("rename Ch0_24G.vbs Ch0_24G.txt");
Sleep(3000);

fstream outfile("Ch0_24G.txt", ios::out | ios::in);
char ch;
char buffer[1000];
int i = 0, k = 0;
if (!outfile) {
cout << "不能打开目的文件:test.txt" << '\n';
exit(1);
}

outfile.unsetf(ios::skipws);
while (outfile >> ch) {//将文件全部内容读出到buffer
buffer[i] = ch;
i++;
}
strstr_rep(buffer, "192.168.1.2", "192.168.4.2");//将"2000"替换为8888"
outfile.close();
ofstream infile("Ch0_24G_bak.txt");
while (k != i) { infile << buffer[k]; k++; }//将buffer全部写入到文件
infile.close();

system("del Ch0_24G.txt");
system("rename Ch0_24G_bak.txt Ch0_24G.vbs");

return 0;
}

posted @   江南王小帅  阅读(41)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示