第14周-閱讀專案1-二進位制檔案的讀寫

kewlgrl發表於2015-06-15

閱讀並執行下面的兩個程式,分別用記事本和二進位制檔案閱讀器(請自行下載Binary Viewer等程式,或者用DOS中的Debug程式,並百度其用法)。檢視其內容,並理解檔案儲存的原理。


問題及程式碼:

#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main( )
{
    int a;
    ofstream outfile("f1.dat",ios::out);
    if(!outfile)      
    {
        cerr<<"open error!"<<endl;
        exit(1);
    }
    cin>>a;
    outfile<<a<<endl;
    outfile.close();   
    return 0;
}



執行結果:



問題及程式碼:

#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main( )
{
    int a;
    ofstream outfile("f2.dat",ios::out|ios::binary);
    if(!outfile)
    {
        cerr<<"open error!"<<endl;
        exit(1);
    }
    cin>>a;
    outfile.write((char*)&a, sizeof(int));
    outfile.close();
    return 0;
}



執行結果:



知識點總結:

二進位制檔案的讀寫。

學習心得:

Binary Viewer很好用的樣子,畢竟二進位制存入後全是亂碼。。

DOS中的Debug程式這個就感覺高大上了,雖然比Binary Viewer麻煩。。

相關文章