可视化 在 c++ 中读取和搜索二进制文件

visual Reading and searching binary files in c++

本文关键字:搜索 二进制文件 读取 c++ 可视化      更新时间:2023-10-16

在学校里,我们正在学习如何在Visual Studio中使用C ++中的二进制文件。这段代码在Visual Studio 2005中完美运行,但在2010 - 2013版本中则不然。它给出了读取冲突错误。所以我希望你们中的一个人能帮助我解决这个问题,因为即使是我的老师也不知道出了什么问题:(错误发生在读取结束时。我已经尝试了不同的ifstream和ofstream方法,但没有成功。

我的代码:

#include <z:/Yoshi On My Mac/Google Drive/School/2013-2014/C-taal/headeryoshi.h>
#define B "z:/Yoshi On My Mac/Google Drive/city.dat"
typedef struct city {
        string zip, name;
};
void add() {
    ofstream file;
    city city;
    titelscherm("ADD CITY");
    cout << "ZIP: ";
    getline(cin, city.zip);
    while (city.zip not_eq "0") {
            cout << "Name: ";
            getline(cin, city.name);
            file.open(B, ios::app | ios::binary);
            file.write((char*)&city, sizeof(city));
            file.close();
            titelscherm("ADD CITY");
            cout << "POSTCODE: ";
            getline(cin, city.zip);
    }
    cout << "city: ";
    file.close();
}
void read() {
    ifstream file;
    city city;
    titelscherm("READ CITY");
    file.open(B, ios::in | ios::binary);
    file.read((char*)&city, sizeof(city));
    while (!file.eof()) {
            cout << city.zip << " ";
            cout << city.name << endl;
            file.read((char*)&city, sizeof(city));
    }
    file.close();
    _getch();      
}
void search() {
    string zip;
    city city;
    ifstream file;
    bool find;
    titelscherm("SEARCH ZIP");
    cout << "ZIP: ";
    getline(cin, zip);
    file.open(B, ios::in | ios::binary);
    if (!file.is_open()){
            cout << "FILE ERROR";
    }
    else {
            do {
                    file.read((char*)&city, sizeof(city));
                    find = (city.zip == zip);
            } while (!file.eof() and !find);
            if (find) {
                    cout << city.name << endl;
            }
            else {
                    cout<<" zit niet in het file" << endl;
            }
    }
    _getch();
    file.close();
}
int main() {
    add();
    read();
    search();
    return 0;
}

我会严重怀疑你老师的C++能力。

不能将std::string作为原始数据读取。 它不是 POD 类型。

file.read((char*)&city, sizeof(city))
...
file.write((char*)&city, sizeof(city));

这段代码以前不应该工作,但听起来你不知何故真的很幸运。

您需要通过写入字符串的长度,后跟实际字符来序列化字符串。 读取时,您将首先读取大小,然后分配存储空间,然后读取字符。

如果要改用方法,请将结构中的string值更改为char数组。