我的任务是将结构保存到二进制文件,然后将文件打印出来以进行控制台。数据正在写入文件,但是当我读取它时,我只会输出第一个单词。我想我的代码中遗漏了一些东西。感谢您的帮助。
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);
}
}
答案 0 :(得分:3)
BOOL readFile = ReadFile(hFile, &buff, sizeof(book), &numberOfBytesToRead, NULL);
cout << buff << endl;
您正在阅读的是char[255]
,而不是Book
结构。因此,书名以\ 0结尾,这就是为什么只打印该书的原因。 cout
对char数组进行操作,而不对结构进行操作。
存储/接收数据的错误方式。容易出现安全问题。