Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

binary files C vs C++

luckyboyluckyboy Posts: 105Member
[b][red]This message was edited by luckyboy at 2006-1-27 23:8:49[/red][/b][hr]
hi all,
please check this and tel me what is wrong:
[code]
#include
int main()
{
FILE *fp;
fp = fopen("test.txt", "wb");
int a = 32;
putw(a, fp);
fclose(fp);
return 0;
}
[/code]
the previous code generates a file when desplaying it in a hex-editor it shows "2000 0000" and that's right "binary data should appear in this manar i.e reversed byte order"

but next code does not do the same
[code]
#include
int main()
{
ofstream f;
f.open("test.txt", ios::binary);
int a = 32;
f << a; // i guess fault is here
f.close();
return 0;
}
[/code]

the question now "does insertion operator << supports only formatted text ?"
and if "yes", how can i use ios::binary ?


Comments

  • DonotaloDonotalo Posts: 715Member
    : [b][red]This message was edited by luckyboy at 2006-1-27 23:8:49[/red][/b][hr]
    : hi all,
    : please check this and tel me what is wrong:
    : [code]
    : #include
    : int main()
    : {
    : FILE *fp;
    : fp = fopen("test.txt", "wb");
    : int a = 32;
    : putw(a, fp);
    : fclose(fp);
    : return 0;
    : }
    : [/code]
    : the previous code generates a file when desplaying it in a hex-editor it shows "2000 0000" and that's right "binary data should appear in this manar i.e reversed byte order"
    :
    : but next code does not do the same
    : [code]
    : #include
    : int main()
    : {
    : ofstream f;
    : f.open("test.txt", ios::binary);
    : int a = 32;
    : f << a; // i guess fault is here
    : f.close();
    : return 0;
    : }
    : [/code]
    :
    : the question now "does insertion operator << supports only formatted text ?"
    : and if "yes", how can i use ios::binary ?
    :
    :
    [purple]yes, u r right. << writes to file formated text. there are several ways to write to a binary file. one of these is shown below:[code]
    #include <fstream.h>
    int main()
    {
    ofstream f;
    f.open("test.txt", ios::binary);
    int a = 32;
    f.write((char*) &a, sizeof(a));
    f.close();
    return 0;
    }
    [/code]
    [/purple]
    [hr][purple]~Donotalo()[/purple]

Sign In or Register to comment.