[英]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.