0
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;
}   

它不会更改文件中的任何内容。并且在打印时它的打印没有任何原因导致它根本不插入第二个(当我只打印时它工作正常)

4

1 回答 1

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: 读取后保存读取位置。写入后恢复读取位置。

于 2013-06-12T19:27:52.813 回答