我有一个.html
文件(input.html)和一个.txt
文件(diff.txt),其中有一些HTML代码。
我从文件diff1.txt读取HTML代码,然后将其保存为字符串。
FILE *filetxt;
long len;
char *buf;
filetxt=fopen("diff1.txt","rb");
fseek(filetxt,0,SEEK_END); //go to end
len=ftell(filetxt); //get length of file
fseek(filetxt,0,SEEK_SET); //go to beg.
buf=(char *)malloc(len);
fread(buf,len,1,filetxt); //read into buffer
如何在input.html?
文件中找到并替换从diff1.txt读取的HTML代码我添加了这个,但我有一个段错误:(
#include <iostream>
#include <fstream>
#include <cstring>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
using namespace std;
char *replace_str(char *str, char *orig, char *rep)
{
static char buffer[4096];
char *p;
if(!(p = strstr(str, orig))) // Is 'orig' even in 'str'?
return str;
strncpy(buffer, str, p-str); // Copy characters from 'str' start to 'orig' st$
buffer[p-str] = '\0';
sprintf(buffer+(p-str), "%s%s", rep, p+strlen(orig));
return buffer;
}
int main()
{
FILE *filetxt;
FILE *filehtml;
long len_txt,len_html;
char *buf_txt, *buf_html;
filetxt=fopen("diff1.txt","rb");
filehtml=fopen("input.txt","rb");
fseek(filetxt,0,SEEK_END); //go to end
fseek(filehtml,0,SEEK_END);
len_txt=ftell(filetxt); //get position at end (length)
len_html=ftell(filehtml);
fseek(filetxt,0,SEEK_SET); //go to beg.
fseek(filehtml,0,SEEK_SET);
buf_txt=(char *)malloc(len_txt); //malloc buffer
buf_html=(char *)malloc(len_html); //malloc buffer
fread(buf_txt,len_txt,1,filetxt); //read into buffer
fread(buf_html,len_html,1,filehtml); //read into buffer
//fwrite(buf_txt,len_txt,1,fp1);
//fwrite(buf_html,len_html,1,fp1);
puts(replace_str(buf_html, buf_txt, " "));
fclose(filetxt);
fclose(filehtml);
return 0;
}