0

I have an .html file (input.html) and a .txt file (diff.txt) in which there is some HTML code.

I read from file diff1.txt the HTML code and I save it in a string.

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

How can I find and replace the HTML code read from diff1.txt, in the file input.html?

I have add this but I have a seg fault :(

#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;
}
Jonas
  • 6,641
  • 8
  • 29
  • 50

0 Answers0