0

我有一个.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;
}
4

0 回答 0