如何使用 WINAPI 读取整个二进制文件

how to read whole binary file with WINAPI?

本文关键字:二进制文件 读取 何使用 WINAPI      更新时间:2023-10-16

我有一个任务将结构保存到二进制文件,然后将文件打印到控制台。数据正在写入文件,但是当我读取它时,我只得到第一个单词的输出。我想我的代码中缺少一些东西。将感谢您的帮助。

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 数组上运行,而不是在结构上运行。

顺便说一句,存储/接收数据的坏方法。容易出现安全问题。