Skip to content
Advertisement

Why does octal dump output the ascii code for an integer variable instead of the binary code?

This is the code in C to input a character and integer variable to a file.

int main(void)
{
    FILE *fp;
    char file[20];
    int i = 40;

    printf("Enter filename: ");
    scanf("%s", file);

    fp = fopen(file, "wb");

    fprintf(fp, "%d", i);
    fprintf(fp, "%c%c", '4', '0');

    fclose(fp);

    return 0;
}

So lets say the file name is text and the od command is invoked..

od -xc text

This is the output of the command

0000000    3034    3034
            4 0     4 0

Why does it print the ASCII values for both of the value 40 and not the hex code 0028 for the integer variable?

Advertisement

Answer

fprintf formats all output as textfprintf( fp, "%d", 42 ) writes the character values '4' and '2' to the output stream, same as fprintf( fp, "%c%c", '4', '2' ) and fprintf( fp, "%s", "42" ).

If you want to write the binary representation of the integer to your output stream, then you need to use fwrite( &i, sizeof i, 1, fp );.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement