Reading binary file in string shows strange output

So, here is my scenario:

I have a binary file, and the information I got is: file size is 1kb, there are only chars in the file, and file is binary.

So, I tried to read and print first 128 chars to test doing like this:

FILE *f;
if((f = fopen(argv[1],"rb")) == NULL){ 
    printf("CANNOT OPEN FILE\n");
    exit(1);
}

char buffer[128];
printf("%d\n",fread(buffer, sizeof(char), 128, f));
printf("%s", buffer);

But the output does not look as a 128 size-long string at all, the output is this: �1X�Z%]X�^ԫ��ƛ�T�tA!=܇p�>�A��g>~���k�*��;�2�

Does anyone know what my mistake was?

Answers


  1. If your file contains non-ASCII characters, the result will look like garbage.

  2. If your read failed, then the buffer will be uninitialized, and the result will look like garbage.

  3. If there is no "NULL" terminator, then some - or all - of your output will look like garbage.

  4. Even if the buffer prints garbage - and there is a NULL character - the output will end at '\0'.

SUGGESTION:

Look at the file in notepad. Or, even better, look at it in a hex editor.

Linux has a "strings" command that will print only the text strings in a binary file. You can download a Windows version of "strings" here:

https://technet.microsoft.com/en-us/sysinternals/strings.aspx


After you read data into buffer, try to print the ASCII codes of the characters. That will indicate whether the characters are printable or not.

char buffer[128];
int n = fread(buffer, sizeof(char), 128, f);
for (int i = 0; i < n; ++i)
{
   printf("i: %d, ASCII code: %d\n", i, buffer[i]);
}

Need Your Help

Scriptfile error

sql sql-server

I am working on a script file that has to display the number of orders.

Signature-preserving Decorator Pattern in C++?

c++ design-patterns boost stl decorator

I'd like to use the Decorator Pattern in C++ and still be able to rely on the signature/identity of the decorated object. Is it possible to do it in C++?