可视化 在 c++ 中读取和搜索二进制文件
visual Reading and searching binary files in 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;
}
我会严重怀疑你老师的C++能力。
不能将std::string
作为原始数据读取。 它不是 POD 类型。
file.read((char*)&city, sizeof(city))
...
file.write((char*)&city, sizeof(city));
这段代码以前不应该工作,但听起来你不知何故真的很幸运。
您需要通过写入字符串的长度,后跟实际字符来序列化字符串。 读取时,您将首先读取大小,然后分配存储空间,然后读取字符。
如果要改用方法,请将结构中的string
值更改为char
数组。
相关文章:
- 正在读取二进制文件(is_open)
- 在C++中将类(带有Vector成员)保存为二进制文件
- 如何从二进制文件中读取字符串
- cmake:添加要搜索头文件的目录
- 保存/加载大量短数组到二进制文件
- 从二进制文件中读取整数数组
- Android 在编译二进制文件时重建静态库
- 在 C++ 中将双精度变量写入二进制文件
- clang 的 libFuzzer 可以在同一二进制文件中测试超过 1 个 API 吗?
- C++:实际上不是从二进制文件中读取
- 如何从二进制文件中的给定符号中获取调用程序图
- 将内部带有矢量的结构保存/读取到二进制文件中
- 在C++中搜索二进制文件分隔符时出现不正确的偏移量
- 可视化 在 c++ 中读取和搜索二进制文件
- 在缓冲区中加载块的大二进制文件中搜索
- 我如何使用find_package使可执行搜索.dll二进制文件
- 从二进制文件中读取和搜索数据
- 用c++在二进制文件中搜索字符串
- 用于在二进制文件中搜索字符串的代码
- 如何在二进制文件中搜索" "?