2010-02-09 137 views
1

我想收缩与浮点值大的文本文件转换成一个二进制.dat文件的大小,所以就用(在C++):二进制.dat文件问题

// the text stream 
std::ifstream fin(sourceFile); 
// the binary output stream 
std::ofstream out(destinationFile, std::ios::binary); 

float val; 
while(!fin.eof()) 
{ 
    fin >> val;  
    out.write((char *)&val,sizeof(float)); 
} 
fin.close(); 
out.close(); 

然后,我想从rpeviously创建的二进制文件中读取所有的浮点值到一个浮点值数组中。 但是,当我尝试从这个文件中读取我在最后一行代码(阅读过程中)得到一个异常:

// test read 
std::ifstream fstream(destinationFile, std::ios::binary); 

__int64 fileSize = 0; 
struct __stat64 fileStat; 
if(0 == _tstat64(destinationFile, &fileStat)) 
{ 
    fileSize = fileStat.st_size; 
} 

//get the number of float tokens in the file 
size_t tokensCount = fileSize/sizeof(float); 
float* pBuff = new float[tokensCount]; 
fstream.read((char*)&pBuff, tokensCount * sizeof(float)); 

我在做什么错?

回答

5
float* pBuff = new float[tokensCount]; 
fstream.read((char*)&pBuff, tokensCount * sizeof(float)); 

您正在读入pBuff变量,而不是它指向的缓冲区。您的意思是:

fstream.read((char*)pBuff, tokensCount * sizeof(float)); 
4

Magnus的回答是正确的,应该可以解决您的问题。我只会补充说,如果你按照专家的说法做了,而不是使用邪恶的C型演员阵容,那么你首先就不会有问题。如果您将最后一行更改为:

fstream.read(static_cast<char*>(&pBuff), tokensCount * sizeof(float)); 

然后,您的程序将无法编译,错误消息将导致您找到解决方案。

编辑:如果pBuff是除char以外的任何类型的指针,我的解决方案不起作用。所以这在OP的情况下是没有用的。

+0

你是对的,但如果我写 fstream.read(的static_cast (PBUFF),tokensCount *的sizeof(浮动)); 它仍然不能编译... – melculetz 2010-02-09 12:27:28

+0

对不起,我只用char * pBuff对其进行了测试,但当pBuff是任何其他类型时,它不起作用。有什么方法可以让我从这些upvotes中获得的代表回复? – Manuel 2010-02-09 12:53:30

+0

别担心。尽管'reinterpret_cast'在这里可能更适合,不管怎么说,使用C++风格的类型转换都是很好的建议。 – 2010-02-10 11:35:45

5

需要注意的是这样的:

while(!fin.eof()) 
{ 
    fin >> val;  
    out.write((char *)&val,sizeof(float)); 
} 

不是读取文件的正确方法 - 将在年底读取垃圾值。你几乎不应该使用eof()函数,你应该总是检查文件读取是否有效。正确的代码是:

while(fin >> val) 
{ 
    out.write((char *)&val,sizeof(float)); 
}