I have this piece of C code:
[...]
struct stat info;
char *filename = "just_a_binary_file";
stat(filename, &info);
printf("FILE SIZE: %d\n", info.st_size);
char *content = (char *)malloc(info.st_size * sizeof(char *));
FILE *fp = fopen(filename, "rb");
fread(content, info.st_size, 1, fp);
fclose(fp);
printf("STRING LENGTH: %d\n", strlen(content));
[...]
the output is:
FILE SIZE: 20481
STRING LENGTH: 6
the problem is that file contains some Zero-Bytes and when I put the file content into a variable char* the string is truncated at the first occurrence of ‘\0’ (chr(0) precisely).
The question is how can I get the full binary content into a variable char*?
First of all, you allocate way too much memory.
info.st_size * sizeof(char)is enough. You store chars, not pointers.Then you need to store the file size and use memory functions instead of string functions. A blob of data that contains null bytes is not a string per definition. So it’s impossible to get its length except by using the already-known file size.