Search code examples
ccharfwrite

C fwrite() writes amount of characters doubled


When I use this code

FILE *f = fopen(file, "wb");
fflush(f);
if (f==NULL) {
    //perror(f);
    return 0;
}
else{
    fwrite(text, sizeof(char), strlen(text), f);
    int i = fprintf(f, "%s", text);
    if (i>0) {
        fclose(f);

        return  1;
    }

(text is const char text[1024000], which is set as one of the arguments in the function) if I write

This is a test
This is a test

to test if it can write multiple lines, it writes this

This is a test
This is a testThis is a test
This is a test

why do I get this weird behavior?


Solution

  • You're writing twice:

    fwrite(text, sizeof(char), strlen(text), f);
    int i = fprintf(f, "%s", text);
    

    Pick one