【发布时间】:2019-12-02 17:46:07
【问题描述】:
我是一个非常缺乏经验的初学者,在尝试将一些数据保存在文件中时遇到了麻烦。我的结构看起来像这样。
struct Appointment {
wchar_t Name[50]; //name of the patient
wchar_t Age[3]; //age of the patient
HWND hwdnd_img; //handler of the image of the patient to be displayed in windows
HBITMAP hbitimg; //hbitmap of the image of the patient
wchar_t wchr_Dirimg[MAX_PATH] = L""; // directory of the image of patient
};
这是我正在尝试编写的Appointment 类型的数组:
Appointment Arraytosave[5];
假设它有这个数据:
Arraytosave[0].Name = L"John";
Arraytosave[0].Age = L"23";
Arraytosave[0].hwdnd_img = example bitmap hwnd;
Arraytosave[0].hbitimg = example hbitmap data;
Arraytosave[0].wchr_Dirimg = L"C:\\Example path";
这是我编写它的代码:
void Save(Appointment* Arraytosave, int elements_in_array) {
wofstream outputF("datos.bin", ios::binary | ios::trunc);
if (!outputF.is_open()) {
MessageBox(NULL, L"Cannot open file", L" SAVE_FILE FAILED", MB_ICONERROR);
}
else {
if (!(elements_in_array== 0)) {
for (int i = 0; i < elements_in_array; i++) {
int sizeName= sizeof(Arraytosave[i].Name);
int sizeAge= sizeof(Arraytosave[i].Age);
int sizehwdnd_img = sizeof(Arraytosave[i].hwdnd_img);
int sizehbitimg = sizeof(Arraytosave[i].hbitimg);
int sizewchr_Dirimg = sizeof(Arraytosave[i].wchr_Dirimg);
outputF.write(reinterpret_cast<wchar_t*>(&Arraytosave[i].Name), sizeName);
outputF.write(reinterpret_cast<wchar_t*>(&Arraytosave[i].Age), sizeAge);
outputF.write(reinterpret_cast<wchar_t*>(&Arraytosave[i].hwdnd_img), sizehwdnd_img );
outputF.write(reinterpret_cast<wchar_t*>(&Arraytosave[i].hbitimg), sizehbitimg );
outputF.write(reinterpret_cast<wchar_t*>(&Arraytosave[i].wchr_Dirimg), sizewchr_Dirimg );
}
outputF.write(reinterpret_cast<wchar_t*>(elements_in_array), sizeof(int));
outputF.close();
}
}
但是当我用记事本检查文件 datos.bin 时,它只显示 Arraytosave[0].Name 而没有其他内容。
John
编辑
好的,所以我下载了“HxD”程序并显示如下
offset(h) 00 01 02 03 04 05 06 07 08 0A 0B 0C 0D 0E 0F Decoded text
00000000 4A 6F 68 6E 00 John.
【问题讨论】:
-
记事本不知道如何显示。试试 HxD
-
@user253751 哦,谢谢。它显示得更好,但是“保存”功能仍然只写“约翰”
-
那是在运行程序之后,对吧?您没有使用记事本或其他任何东西保存和加载它吗?顺便说一句,十六进制代码说“乔恩”,但我认为这只是复制它的一个错误。如果你使用 ofstream 而不是 wofstream 会怎样?
-
@user253751 是的,我删除了“datos.bin”,然后再次运行程序,然后程序创建了文件。它仍然只打印 [0] 元素的 .Name 。 (对不起,如果我没有很好地解释自己,我的英语不是很好)
-
通常存储句柄(例如 HWND、HBITMAP)是没有意义的。相反,您应该存储句柄代表的任何数据。因此,如果您有图像句柄,请存储图像,而不是该图像的句柄。
标签: c++ winapi visual-c++