Bruce
Bruce

Reputation: 35233

Formatted output and fprintf

I wrote this small C program:

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

int main()
{
 FILE * fp;
 fp = fopen("data.txt","w");
 fprintf(fp,"%d",578); 
 return 0;
}

Then I analyzed data.txt using xxd -b. I was expecting that I will see the 32 bit representation of 578 instead I saw the ASCII representation of 578:

xxd -b data.txt
0000000: 00110101 00110111 00111000                             578

Why is that? How do I store the 32 bit representation of 578 (01000010 00000010 00000000 00000000) assuming little endian?

Upvotes: 3

Views: 261

Answers (4)

littleadv
littleadv

Reputation: 20272

That's the meaning of "Formatted". You used qualifier %d which means "format the given value as its ASCII numeric representation in the execution character set, assuming the value is a signed integer".

If you want to write binary data into a file - don't use formatted output. Use fwrite instead to write raw binary data.

Upvotes: 3

sarnold
sarnold

Reputation: 104050

If you want to write raw data to a file using the standard IO facilities, you're looking for fwrite(3):

$ cat numbers.c
#include <stdio.h>

int main(int argc, char* argv[]) {
    int i = 578;
    long l = 578;
    float f = 5.78;
    double d = .578;
    long marker = 0xFFFFFFFFFFFFFFFF;


    FILE *fp = fopen("data", "w");
    fwrite(&i, sizeof i, 1, fp);
    fwrite(&marker, sizeof marker, 1, fp);
    fwrite(&l, sizeof l, 1, fp);
    fwrite(&marker, sizeof marker, 1, fp);
    fwrite(&f, sizeof f, 1, fp);
    fwrite(&marker, sizeof marker, 1, fp);
    fwrite(&d, sizeof d, 1, fp);
    fclose(fp);
    return 0;
}
$ make numbers
cc     numbers.c   -o numbers
$ ./numbers 
$ xxd data
0000000: 4202 0000 ffff ffff ffff ffff 4202 0000  B...........B...
0000010: 0000 0000 ffff ffff ffff ffff c3f5 b840  ...............@
0000020: ffff ffff ffff ffff e5d0 22db f97e e23f  .........."..~.?
$ xxd -b data
0000000: 01000010 00000010 00000000 00000000 11111111 11111111  B.....
0000006: 11111111 11111111 11111111 11111111 11111111 11111111  ......
000000c: 01000010 00000010 00000000 00000000 00000000 00000000  B.....
0000012: 00000000 00000000 11111111 11111111 11111111 11111111  ......
0000018: 11111111 11111111 11111111 11111111 11000011 11110101  ......
000001e: 10111000 01000000 11111111 11111111 11111111 11111111  .@....
0000024: 11111111 11111111 11111111 11111111 11100101 11010000  ......
000002a: 00100010 11011011 11111001 01111110 11100010 00111111  "..~.?
$ 

Upvotes: 1

abelenky
abelenky

Reputation: 64682

You'll want to look at fwrite.

int myNum = 578;
fwrite( &myNum, sizeof(int), 1, fp);

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 477030

Use fwrite:

uint32_t n = 578;
fwrite(&n, sizeof n, 1, fp);

fprintf is for formatted output, whence the trailing f.

Upvotes: 5

Related Questions