Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File Size to store an integer

I want to write an integer (for ex - 222222) to a text file in a way that the size of the file is reduced. If I write the integer in the form of a string, it takes 6 Bytes because of the six characters present. If I store the integer in the form of an integer, it again takes 6 Bytes. Why isn't the file size equal to 4 Bytes since an int takes 4 Bytes?

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

using namespace std;

int main()
{
    //char* x = "222222.2222";
    //double x = 222222.2222;
    int x = 222222;
    FILE *fp = fopen("now.txt","w");
    fprintf(fp,"%d",x);
    return 0;
}
like image 887
Hellboy Avatar asked Feb 19 '26 01:02

Hellboy


1 Answers

Here is the definition of fprintf:

writes the C string pointed by format to the stream. 

So whatever you pass to the function, they are treated as a string, that's the output file all has 222222 stored in it.

If you want to store a integer rather than a string in the file, you could use: fwrite.

int x = 222222;
FILE *fp = fopen("now.txt","w");
fwrite(&x, sizeof(int), 1, fp);

Then the file stores: 0E 64 03 00 if you change you editor to hex mode. It's 4 bytes.

like image 63
feihu Avatar answered Feb 20 '26 13:02

feihu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!