2012-04-01 19 views
1

我試圖導出各種值,如int和簡單的結構,以二進制文件。這裏有一些代碼:ostream ::寫不寫整個結構?

#include &ltiostream> 
#include &ltfstream> 
#include &ltcstdint> 
using namespace std; 

template&ltclass T> void writeToStream(ostream& o, T& val) 
{ 
    o.write((char*)&val, sizeof(T)); 
    cout << o.tellp() << endl; //always outputs 4 
} 

struct foo { 
    uint16_t a, b; 
}; 

int main() 
{ 
    foo myFoo = {42, 42}; 
    ofstream test("test.txt", ios::binary); 
    writeToStream(test, myFoo); 
    test.close(); 
}

該程序應該生成一個輸出文件4個字節長。但是當我打開它時,它只有2個字節長。如果我將myFoo.amyFoo.b更改爲包含256或更多值(需要多個字節進行存儲),則該文件將變爲4個字節長。我在Win7上使用Visual Studio 11 Developer Preview;我沒有檢查過其他系統或編譯器是否發生了相同的情況。我怎樣才能使它輸出正確的值爲256或以下的a或b?

+0

你如何確定文件的長度? – 2012-04-01 01:06:29

+0

那麼,我打開它在記事本+ +,它顯示爲2個字符的值在256下,否則4。但是,如果我右鍵單擊該文件並單擊「屬性」它將顯示我4個字節... – Mark 2012-04-01 01:10:23

+3

我認爲其中存在您的問題;您正嘗試通過在文本編輯器中查看來確定二進制文件大小。 – 2012-04-01 01:11:47

回答

2

一個文件只能被一個程序讀回來,該程序理解它的存儲格式。記事本++不知道文件的存儲格式,因此它無法讀取併合理呈現它。要麼以Notepad ++理解的格式(例如ASCII文本)寫入文件,要麼只使用瞭解您寫入的格式的程序來讀取文件。

+0

或通過使用文件瀏覽器或終端命令來確定文件大小... – Potatoswatter 2012-04-01 01:34:04

+0

我想我被拋棄了,因爲記事本++通常顯示我空字符和那種東西。但是,我用十六進制編輯器確認Notepad ++是錯誤的。 – Mark 2012-04-01 04:03:33

0

我已清理完您的代碼,如下所示。雖然我不知道爲什麼舊代碼輸出兩個字節,但新代碼確實輸出了四個字節。

#include <iostream> 
#include <fstream> 
#include <cstdint> 
using std::cout; 
using std::endl; 
using std::uint16_t; 
using std::ostream; 
using std::ofstream; 
using std::ios; 

template <class T> void writeToStream(ostream& o, T& val) 
{ 
    o.write(reinterpret_cast<char *>(&val), sizeof(T)); 
    cout << o.tellp() << endl; //always outputs 4 
} 

struct foo { 
    uint16_t a, b; 
}; 

int main() 
{ 
    foo myFoo = {42, 42}; 
    ofstream test("test.txt", ios::binary); 
    writeToStream(test, myFoo); 
    // Just let the stream "test" pass out of scope. 
    // It closes automatically. 
    //test.close(); 
    return 0; 
} 

(我的標準庫沒有cstdint,所以我用short而不是uint16_t,但我懷疑這事。)

std::ofstream類型從std::ostream的。如果通過簡單的std::ostream,則writeToStream()函數更快樂,或者至少更規則更通用。此外,對於信息:發佈using namespace std;幾乎從未在C++中推薦。

祝你好運。

+1

看起來你的程序和他的程序是一樣的,它的工作原理是因爲他已經工作了。 – Potatoswatter 2012-04-01 01:34:37