2014-10-10 72 views
1

我確定這肯定是一個常見問題,但似乎無法找到等價的問題*或示例。從C++中的4字節[二進制文件I/O]構建32位浮點數

我有一個二進制文件,是一系列4字節的浮點數。我讀入一個由文件長度決定的矢量(除以我的浮點數)。我使用了another post的bytesToFloat方法。打印出數據時,我的代碼爲所有數據點返回相同的值。怎麼了?

*對不起,管理員,如果我錯過了它。

#include <cstdio> 
#include <cstdlib> 
#include <iostream> 
#include <fstream> 
#include <vector> 

using namespace std; 

typedef unsigned char uchar; 

float bytesToFloat(uchar b0, uchar b1, uchar b2, uchar b3); 

int main() 
{ 
int i,j; 
char u[4]; 
// Open file 
ifstream file; 
file.open("file.dat"); 
// Find file size in bytes 
file.seekg(0,ios::end); 
double size = 0; 
size = file.tellg(); 
file.seekg(0,ios::beg); 

vector<float> data; 
data.resize(size/4); 
i=0; 
while(i<size/4) 
{ 
    j=0; 
    while(j<4) 
    { 
     file.read(&u[j],1); 
     j++; 
    } 
    data[i] = bytesToFloat(u[0],u[1],u[2],u[3]); 

    cout << data[i]<< endl; 
    i++; 
} 

// End program 
file.close(); 
return 0; 
} 

float bytesToFloat(uchar b0, uchar b1, uchar b2, uchar b3) 
{ 
float output; 

*((uchar*)(&output) + 3) = b0; 
*((uchar*)(&output) + 2) = b1; 
*((uchar*)(&output) + 1) = b2; 
*((uchar*)(&output) + 0) = b3; 

return output; 
} 
+0

如果你放棄所有這些循環,並執行'file.read(&data [0],size);'(在調整resize'之後)會發生什麼?當你處於這個狀態時,使'size'成爲一個整數。另外,你怎麼知道你的文件不**實際上包含相同值的副本? – 2014-10-11 01:10:32

+0

我嘗試了file.read方法,它只輸出十六進制值而不是浮點本身。這就是爲什麼我試圖重新構造它的單個字節的浮點數。 我在Visual Studio中打開文件,並且十六進制值不同。它也是從我寫的另一段代碼中隨機生成的,它生成一系列隨機的浮點數(並且已經檢查了該程序的輸出)。 – 2014-10-13 08:51:51

+0

你是什麼意思,「它只輸出」? 'read'不輸出任何內容。 – 2014-10-13 15:15:19

回答

0

因此,經過一番努力和伊戈爾的評論,我能夠解決這個問題。以下函數將所有內容讀入緩衝區向量。

vector<char> buffer; 

void fill() { 
string filename = ""; 
cout << "Please enter a filename:\n>"; 
getline(cin, filename); 

ifstream file(filename.c_str()); 

if (file) { 
    file.seekg(0,std::ios::end); 
    streampos length = file.tellg(); 
    cout<< length << endl; 
    file.seekg(0,std::ios::beg); 
    file.seekg(540,'\0'); 

    length-=540; 
    buffer.resize(length); 
    file.read(&buffer[0],length); 
} 
} 

然後稍後我會在循環中調用bytesToFloat。 bytesToFloat的字節順序是不正確的,所以現在已經顛倒過來了,它輸出和我原始文件相同的值(我把我的隨機文件生成器輸出爲純文本版本進行比較)。

+0

您是否想要跳過文件的前540個字節?這就是'file.seekg(540,'\ 0');'做的。在任何情況下,我都非常肯定'file.read((char *)&data [0],length)'會產生相同的效果('data'是'vector ',適當調整大小),而不需要'bytesToFloat'。 – 2014-10-13 15:18:15

+0

我正在跳過文件中的固定字節長度的標題(爲簡單起見,我沒有提到過)。我嘗試過使用你之前建議的方法,但無法使其正常工作(我一直在將轉換爲char的過程中遇到錯誤)。 – 2014-10-14 10:37:22

+0

您計算「長度」的方式不包含此固定標題。是的,我忘了需要在我最初的建議中使用char *'。通過演員陣容,你應該能夠直接讀入「數據」。 – 2014-10-14 14:08:55

相關問題