create a binary file in C

1.5k views Asked by At

I'm currently working on a binary file creation. Here is what I have tried.

Example 1:

#include<stdio.h>

int main() {
    /* Create the file */
    int a = 5;
    FILE *fp = fopen ("file.bin", "wb");
    if (fp == NULL)
      return -1;
    fwrite (&a, sizeof (a), 1, fp);
    fclose (fp);
    }

    return 0;
}

Example 2:

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

int main()
{
    FILE *fp;
    char str[256] = {'\0'};
    strcpy(str, "3aae71a74243fb7a2bb9b594c9ea3ab4");
    fp = fopen("file.bin", "wb");
    if(fp == NULL)
        return -1;
    fwrite(str, sizeof str, 1, fp);
    return 0;
}

Example 1 gives the right output in binary form. But Example 2 where I'm passing string doesn't give me right output. It writes the input string which I have given into the file and appends some data(binary form).

I don't understand and I'm unable to figure it out what mistake I'm doing.

2

There are 2 answers

0
Jeremy West On

The problem is that sizeof str is 256, that is, the entire size of the locally declared character array. However, the data you are storing in it does not require all 256 characters. The result is that the write operation writes all the characters of the string plus whatever garbage happened to be in the character array already. Try the following line as a fix:

fwrite(str, strlen(str), 1, fp);
0
Sergey Kalinichenko On

C strings are null terminated, meaning that anything after the '\0' character must be ignored. If you read the file written by Example 2 into a str[256] and print it out using printf("%s", str), you would get the original string back with no extra characters, because null terminator would be read into the buffer as well, providing proper termination for the string.

The reason you get the extra "garbage" in the output is that fwrite does not interpret str[] array as a C string. It interprets it as a buffer of size 256. Text editors do not interpret null character as a terminator, so random characters from str get written to the file.

If you want the string written to the file to end at the last valid character, use strlen(str) for the size in the call of fwrite.