xor
xor

Reputation: 2698

saving data to binary file

How much space a character takes when saving it to file in binary mode [8 bits or 12 bits]?

fprintf(f,"%ld",ch);

also if I save a long [say 5] then how much space it gonna take 3bits [101] or 8bits[00000101]

Upvotes: 0

Views: 147

Answers (3)

waynix
waynix

Reputation: 521

fprintf(f,"%ld",...)

will convert your number to a decimal number and will take log_10(ch) bytes to store. When you store it with fwrite it will take as much bytes as you specify.

fwrite (buffer , 1 , sizeof(buffer) , f )

Also attention as you will never store single bits to a file as the read write acess is bytewise and therefore always a multiple of 8.

Upvotes: 4

teppic
teppic

Reputation: 8195

It copies the number of bytes required to store a long on your platform (sizeof (long)). If it copied just the bits required to represent the number, you'd have no way of interpreting the data when reading it.

In your code though, you're copying to a string. So the character (probably ASCII) representation would be stored, not the binary number.

Upvotes: 1

ppeterka
ppeterka

Reputation: 20726

There is a good helping tool you need for this: sizeof Wiki article

Quote:

In the programming languages C and C++, the unary operator sizeof is used to calculate the size of any datatype, measured in the number of bytes required to represent the type. A byte in this context is the same as an unsigned char, and may be larger than 8 bits, although that is uncommon. The result of sizeof is the size of the type of the expression or parenthesized type-specifier that it precedes, and has an unsigned integral type which is usually denoted by size_t. sizeof can be applied to any datatype, including primitive types such as integer and floating-point types, pointer types, or compound datatypes (unions, structs, or C++ classes).

So basically: if you want to know how many bytes something will use, just use the sizeof.

Be careful however: pointers, and other elements that are in fact pointers, but are used differently (like arrays) only show the size of the pointer in bytes... Not the structure the pointer points to! And storing a pointer is of very limited use - next time the object you want to use might be in a different location in the memory.

Upvotes: 1

Related Questions