0

我有一个结构:

    struct zipType{
    int postalCode;
    double longitude;
    double latitude;  
    };

我有一个名为 zipToCout 的函数:

    void zipToCout(zipType zip){
    cout << "Postal Code = " << zip.postalCode << "\tLongitude = " << zip.longitude << "\t\tLatitude = " << zip.latitude << endl;
    }

现在我需要一个函数来将二进制文件读入 zipType 结构。函数原型应该是void binRead(zipType *zip, fstream *input);. 我可以接近这一点的唯一方法是将原型更改为 this void binRead(zipType &zip, fstream &input)。有了这个,这是我目前拥有的功能:

    void binRead(zipType &zip, fstream &input){
    int temp;
    double temp2;
    zipType tempZip;
    tempZip = zip;
    //cout << "Reader at location " << input.tellg() << endl;
    input.read((char*)&temp,sizeof(int));
    tempZip.postalCode=temp;
    input.read((char*)&temp2,sizeof(double));
    tempZip.longitude=temp2;
    input.read((char*)&temp2,sizeof(double));
    tempZip.latitude=temp2;
    zipToCout(tempZip);
    }

这是我在我的 sample.bin 文件上运行它时得到的输出:

    Postal Code = 64501     Longitude = 2.61457e-261                Latitude = -7.13357e+288

我需要帮助的是重新格式化函数以使用*'s 而不是&'s 并修复如何正确地将文件读入三个变量。感谢您的关注!此外,此时我只需从文件中读取一个 zipType。

4

2 回答 2

0
void binRead(zipType *zip, fstream *input)
{
    input->read((char*)( &zip->postalCode ),  sizeof(int   ));
    input->read((char*)( &zip->longitude  ),  sizeof(double));
    input->read((char*)( &zip->latitude   ),  sizeof(double));
    zipToCout(*zip);
}

此外,根据架构(即 32 位 x86),以下可能有效:

void binRead(zipType *zip, fstream *input)
{
    input->read((char*) zip, sizeof(zipType));
    zipToCout(*zip);
}

这仅适用于double仅需要 4 字节对齐的架构。我相信 32 位 x86 适合这一点。我在当地写的一个快速测试表明情况就是这样。

关于超出上述即时需求的可移植、可维护代码的快速说明:当保存数据的机器与稍后读取数据的机器相同时,上述代码运行良好。但是,它确实会导致可移植性问题。如果您真的想设计一种可跨机器移植并保留数据的文件格式,那么上述技术并不真正有利于实现这一点。

于 2013-11-14T03:02:10.637 回答
0

我认为问题出在打印值时。如果您看到该值以字符串形式读取并打印为其他数据类型。我想正确的转换功能应该适合你。并使用请参阅下面的评论。

void binRead(zipType &zip, fstream &input){
    char* temp = NULL
    char* temp2 = NULL;
    zipType tempZip;
    tempZip = zip; 
    //cout << "Reader at location " << input.tellg() << endl;
    input.read(temp,sizeof(int));
    tempZip.postalCode=(atoi)temp; //use for proper conversion, or other function
    input.read(temp2,sizeof(double));
    tempZip.longitude=static_cast<double*>temp2; //use for proper conversion, or other function
    input.read(temp2,sizeof(double));
    tempZip.latitude=static_cast<double*>temp2; 
    zipToCout(tempZip);
    }

对上述代码的评论很少,

tempZip = zip; //why this, since you havn't declared any proper assignment 
operator. Use memcpy instead.  

tempZip.postalCode=(atoi)temp; //use for proper conversion, or other function

tempZip.longitude=static_cast<double*>temp2; //use for proper conversion, or other function

让我知道这是否可以解决您的问题。

于 2013-11-14T03:23:58.667 回答