[英]how to read whole binary file with WINAPI?
I have a task to save structure to binary file and then print out the file to console. 我的任务是将结构保存到二进制文件,然后将文件打印出来以进行控制台。 Data is being written to a file, but when I read it I get output only first word.
数据正在写入文件,但是当我读取它时,我只会输出第一个单词。 I guess I'm missing something in my code.
我想我的代码中遗漏了一些东西。 Will appreciate your help.
将感谢您的帮助。
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;
You are reading to a char[255]
, not a Book
structure. 您正在读取的是
char[255]
,而不是Book
结构。 Hence the title of the book ends with an \\0, that's why only that is printed. 因此,书名以\\ 0结尾,这就是为什么只打印该书的原因。
cout
operates on a char array, not on the structure. cout
在char数组上而不是在结构上运行。
Bad way to store/receive data btw. 糟糕的是存储/接收数据的方法。 Prone to security issues.
容易出现安全问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.