簡體   English   中英

如何使用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數組上而不是在結構上運行。

糟糕的是存儲/接收數據的方法。 容易出現安全問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM