레코드를 사용하여 이진 파일을 읽고 쓰고 싶은 파일이 있습니다. 처음에는 빈 파일이 있는데 새 레코드를 추가하고 싶습니다. 그러나 seekp 함수를 사용하면 위치는 (-1)입니다. 괜찮습니까? 체크 할 때 파일에 아무 것도 쓰지 않았 음을 알기 때문입니다. 코드를 참조하십시오 :C++의 오버플로 체인에서 fstream 파일 작업
void Library::addBook(Book newBook)
{
fstream dataFile;
dataFile.open("BookData.dat", ios::in | ios::out);
if (!dataFile)
{
cerr << "File could not be opened" << endl;
}
int hashResult = newBook.getId() % 4 + 1; // The result of the hash function
// Find the right place to place the new book
dataFile.seekg((hashResult - 1) * sizeof(Book), ios::beg);
Book readBook;
dataFile.read(reinterpret_cast<char*>(&readBook), sizeof(Book));
// The record doesnt exist or it has been deleted
if (readBook.getId() == -1)
{
// The record doesnt exist
if (readBook.getIdPtr() == -1)
{
dataFile.seekp((hashResult - 1) * sizeof(Book));
dataFile.write(reinterpret_cast<char*>(&newBook), sizeof(Book));
}
// The record has been deleted or there is already such record with such hash function
// so we need to follow the pointer to the overflow file
else
{
newBook.setIsBookInData(false); // New book is in overflow file
overflowFile.seekg((readBook.getIdPtr() - 1) * sizeof(Book));
overflowFile.read(reinterpret_cast<char*>(&readBook), sizeof(Book));
// Follow the chain
while (readBook.getIdPtr() != -1)
{
overflowFile.seekg((readBook.getIdPtr() - 1) * sizeof(Book));
overflowFile.read(reinterpret_cast<char*>(&readBook), sizeof(Book));
}
readBook.setIdPtr(header); // Make the pointer to point to the new book
overflowFile.seekp((header - 1) * sizeof(Book));
overflowFile.write(reinterpret_cast<char*>(&newBook), sizeof(Book));
header++;
}
}
누군가가 내가 파일을 쓸 수없는 이유를 말해 줄 수 있다면 정말 그것을 appriciate 할 것입니다. 사전에
감사합니다,
그렉
: (해결 방법을 모른다는 사람이 있습니까? –
숙제가 아니라면 왜 직렬화가 필요한지'Boost.Serialization', 바이너리 데이터 교환을위한'Google Protocol Buffers ' 프로그램 (또는 XML 용 라이브러리, 텍스트 형식이 허용되는 경우 JSON), 경량 데이터베이스 솔루션 용 'sqlite'? – jfs