eefefefe
eefefefe

Reputation: 13

Writing to a Binary file in C, interpreting output

I'm trying to test writing to a binary file in c, and just want to make sense of my output.

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

void writeToFile();

int main(void) {

    writeToFile();

    return(0);
}

void writeToFile() {
    FILE * file = fopen("file.bin","w");
    char * string;

    if(file == NULL)
        printf("Problem with file\n");

    string = malloc(sizeof(char)*6);

    strcpy(string,"Hello");

    fwrite(&string,sizeof(string),strlen(string)+1,file);

    fclose(file);

}

I'm interpreting my results using the commands:

od -c file.bin

Which displays octal output. And gives me this:

0000000   @ 022   # 001  \0  \0  \0  \0 020 020   # 001  \0  \0  \0  \0                                                                                         
0000020 300 016 374   ? 377 177  \0  \0 264 006   @  \0  \0  \0  \0  \0                                                                                         
0000040   @  \a   @  \0  \0  \0  \0  \0 200 365   c 274 020 177  \0  \0                                                                                         
0000060

I'm not sure how to interpret this output, I know it's in octal, but how do I know my string "Hello" was written correctly?

I was thinking I could convert the output to ascii using an ascii table, but I'm not sure if that's doable here? Is there a simple way I can check if string "Hello" was written correctly?

Maybe I could read the output back in, and somehow check if the string "Hello" exists within it?

Any help would be much appreciated.

Upvotes: 1

Views: 128

Answers (2)

Ed Heal
Ed Heal

Reputation: 60047

The line

 fwrite(&string,sizeof(string),strlen(string)+1,file);

should be

 fwrite(string, strlen(string)+1, 1, file);

Because

  1. You already have a pointer to the item - do not need the pointer to that pointer - hence string and not &string
  2. The size of the item is strlen(string) +
  3. You have one item

This is why you are getting output that does not make sense as it is random stuff in memory.

EDIT

ALso

if(file == NULL)
    printf("Problem with file\n");

should be

if(file == NULL) {
    printf("Problem with file\n");
    return;
 }

as there is little that can be done with a null file in the rest of the function

Upvotes: 3

Openeye
Openeye

Reputation: 43

To write to file in binary you should use the "wb" option, for write byte.

FILE * file = fopen("file.bin","wb");

As for knowing if the file is written correctly, the bulletproof way, (allthough probably it exits a better one) is simply to read the file back in with "rb" and print it in normal format.

Upvotes: 1

Related Questions