0

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?

Chris Loonam
  • 5,735
  • 6
  • 41
  • 63

2 Answers2

5

You're writing twice:

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

Pick one

Martin
  • 6,632
  • 4
  • 25
  • 28
0

These two lines write "text" twice. They do same thing.

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

The only difference is fprintf write one more byte '\0' than fwrite.

TieDad
  • 9,143
  • 5
  • 32
  • 58