Home > Enterprise >  Edit file (html) in a stream (C )
Edit file (html) in a stream (C )

Time:06-10

I'm looking for some help for my new project and I'm absolute new in programming in C .

I've a html template (size ~ 8kb) with some placeholders inside. My task is to read this template edit the placeholders and add some or less containers depending on my source.

I tried different ways but always get stucked on a different point.

1:

void readHTML1()
{
    stringstream text;
    ifstream in_file("index.html");

    text << in_file.rdbuf();
    string str = text.str();
    string str_search = "[CREATE_DATE]";
    string str_replace = "12:19 24.05.2022";
    size_t pos = str.find(str_search);
    str.replace(pos, string(str_search).length(), str_replace);
    in_file.close();
    
    ofstream out_file("index_edit.html");
    out_file << str;
}
void readHTML2() {
    FILE * stream;
    stream = fopen("index_edit.html", "r ");
    char line [1000];

    if (stream) {
        if (fgets(line, sizeof(line), stream) == NULL) {
            printf("fgets error\n");
        } else {
            fseek(stream, 31, SEEK_CUR);
            char input[] = "hugo";
            fwrite(input, 4, 1, stream);
        }
        fclose(stream);
    }
}
  1. The replace of the placeholder works fine, but only a part of the whole stream (html file) will be stored in the "out_file". The rest get lost. I speake about a file size of 8kb but it seems to me that is not the problem.

  2. The output is "complete" so the whole stream will be written. But replacing the placeholders overwrites some parts that I don't want to. Is the placeholder smaller then the new value, the rest signs after the placeholder overwrites parts after the placeholders.

I prefere the first variant because it is easier for me to replace the placeholders with the new inputs. But I hope you can help me to understand my first, maybe faulty, steps in this new world (for me). Thank you for your time. I appreciate it. I'm ready to learn ...

CodePudding user response:

I found a solution or better the problem. I always test the first point by using the debug function. And always stop at the line after

out_file << str;

But to this position, for whatever reason (maybe someone can explain!?), only a part of the file was written. So I had never run my code to the end. Now I have run it through and it works. Thanks anyway for your time.

  • Related