用c ++读取和搜索二进制文件

Yos*_*ers 0 c++ binary visual-c++

在学校,我们正在学习如何在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;
}
Run Code Online (Sandbox Code Playgroud)

pad*_*ddy 5

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

您无法读取std::string原始数据.它不是POD类型.

file.read((char*)&city, sizeof(city))
...
file.write((char*)&city, sizeof(city));
Run Code Online (Sandbox Code Playgroud)

这段代码以前不应该有用,但听起来你真的很幸运.

您需要通过写出它们的长度来序列化字符串,然后是实际的字符.阅读时,您将首先读取大小,然后分配存储,然后读取字符.

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

  • 如果我是你,我会找到另一位老师.你提供的代码是一个绝对基本的禁忌.在C++中甚至没有一半能胜任的人都会犯这个错误.我很抱歉强调这一点,但我很惊讶.这是一个链接到我写的关于序列化一些标准容器的旧答案:http://stackoverflow.com/a/12416447/1553090.向下滚动以查找序列化字符串的代码. (2认同)