如何使用 WINAPI 读取整个二进制文件
how to read whole binary file with WINAPI?
我有一个任务将结构保存到二进制文件,然后将文件打印到控制台。数据正在写入文件,但是当我读取它时,我只得到第一个单词的输出。我想我的代码中缺少一些东西。将感谢您的帮助。
struct Book
{
char bookName[40];
char author[40];
float rating;
};
Book book;
int bookAmount = 2;
for (int i = 0; i < bookAmount; i++){
cout << "Book Name: ";
cin >> book.bookName;
cout << "Book Author: ";
cin >> book.author;
cout << "Rating: ";
cin >> book.rating;
DWORD dwBytesWritten;
BOOL writeFile = WriteFile(hFile, &book, sizeof(book), &dwBytesWritten, NULL);
}
DWORD numberOfBytesToRead;
char buff[255];
HANDLE hFile = CreateFile("file.dat", GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
BOOL readFile = ReadFile(hFile, &buff, sizeof(book), &numberOfBytesToRead, NULL);
if (readFile != 0) {
while (numberOfBytesToRead != 0) {
cout << buff << endl;
ReadFile(hFile, &buff, sizeof(book), &numberOfBytesToRead, NULL);
}
}
BOOL readFile = ReadFile(hFile, &buff, sizeof(book), &numberOfBytesToRead, NULL);
cout << buff << endl;
您正在阅读char[255]
,而不是Book
结构。因此,书名以\0结尾,这就是为什么只打印它的原因。 cout
在 char 数组上运行,而不是在结构上运行。
顺便说一句,存储/接收数据的坏方法。容易出现安全问题。
相关文章:
- 如何在 c++ 中将二进制文件读取为字符串
- 从二进制文件读取到数组:前面的任意数字
- 提升二进制文件读取错误不支持的版本
- 无法将二进制文件读取到 std::vector<std::byte> 中C++
- 提升序列化在从二进制文件读取时引发异常
- 从二进制文件 C++ 读取的字符串数组写入
- 将二进制文件读取到 std::vector<bool>
- 将fortran生成的二进制文件读取到C++中的带符号整数数组中
- 将从二进制文件读取的字符串转换为整数
- 从/到C 的二进制文件读取和写作整数
- 通过将结构信息从二进制文件读取到数组中,然后返回到文件C
- 将 int 的二进制文件读取到字符串 c++
- 将结构从二进制文件读取到链表,导致无限循环
- 将二进制文件读取到向量元素的地址中
- c++从二进制文件读取/写入类
- Python:将二进制文件读取到一个结构中,然后拆包
- 从二进制文件读取/写入十六进制字节
- 简单的 C++ 二进制文件读取
- 从二进制文件 c++ 读取 16 位整数
- 如何优化c++二进制文件读取