transactionsFile.seekp(0,transactionsFile.beg);
transactionsFile.seekg(0,transactionsFile.beg);
while (!transactionsFile.eof()){
transactionsFile.read((char*) &tempTrans, sizeof(Transaction));
tempTrans.amount = 50;
transactionsFile.write((char*) &tempTrans, sizeof(Transaction));
}
transactionsFile.seekg(0,transactionsFile.beg);
while (!transactionsFile.eof()){
transactionsFile.read((char*) &tempTrans, sizeof(Transaction));
cout << tempTrans.transID <<" " << tempTrans.amount <<" "<< tempTrans.creditAcctID <<" "<< tempTrans.debitAcctID <<endl;
}
它不会改变文件中的任何内容。 并且在打印时它的打印没有任何原因导致它根本不插入第二个 (当我只做印刷它工作正常)
答案 0 :(得分:0)
当您从文件中read
时,它会将文件指针前进到下一个位置
要写入您阅读的同一条记录,您需要备份到读取开始和写入的位置。
std::streampos read_posn = transactionsFile.tellg();
while (transactionsFile.read((char*) &tempTrans, sizeof(Transaction)))
{
std::streampos next_read_posn = transactionsFile.tellg();
tempTrans.amount = 50;
transactionsFile.seekp(read_posn);
transactionsFile.write((char *) &tempTrans, sizeof(Transaction));
transactionsFile.seekg(next_read_posn);
read_posn = next_read_posn;
}
编辑1:读取后保存读取位置。写入后恢复读取位置。