When writing to a binary file with a fwrite function!

Asked 2 years ago, Updated 2 years ago, 42 views

#include <stdio.h>

int main(){
    FILE * fp;
    char* a="all_new";
    fp=fopen(data.bin,"wb+");
    fwrite(a,200,1,fp);

}

I saw the data.bin

There are trash values. I want to fill up the parts that exceed 7 with CC CC CC... What should I do?

stdio.h visual-studio

2022-09-21 20:12

1 Answers

A is 8 bytes including NULL characters, but it's a problem because I wrote 200 bytes in the file.

#include <stdio.h>
#include <string.h>

int main(){
    FILE * fp;
    char a[200];
    memset(a, 0xCC, sizeof(a));
    strcpy(a, "all_new");
    fp=fopen("data.bin","wb+");
    fwrite(a,200,1,fp);
    fclose(fp);
}

memset is a function that initializes the buffer to the specified character. Doing so as above will initialize the a buffer to 0xCC. strcpy is a command that copies a string Copy "all_new" to the a buffer. And he added the part that closes the file at the bottom.


2022-09-21 20:12

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.