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.
od -Ax -t x1string(not the thing it points to, which is the string), and a bunch of garbage that happens to be after it.wbinstead ofwif you wish to have complete control of what is read and written. Usingfopen()withwonly is not suitable for binary mode.