Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatted output and fprintf

Tags:

c

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?

like image 800
Bruce Avatar asked Jan 27 '26 01:01

Bruce


2 Answers

Use fwrite:

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

fprintf is for formatted output, whence the trailing f.

like image 179
Kerrek SB Avatar answered Jan 28 '26 15:01

Kerrek SB


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.

like image 44
littleadv Avatar answered Jan 28 '26 17:01

littleadv