gpt4 book ai didi

c++ - 附加随机访问文件

转载 作者:太空宇宙 更新时间:2023-11-04 12:14:42 26 4
gpt4 key购买 nike

我在附加到随机访问文件时遇到问题。我似乎无法覆盖文件中的字段。相反,我只是附加到文件,并保持旧名称不变。

fstream Airline("AirLine.text", ios::out | ios::in | ios::app | ios::binary); 
if(!Airline)
{
cout << "File Could not be opened." << endl;
system("PAUSE");
exit (1);
}

cout << "Enter Seat Number to Update" << "(1 to 100, 0 to end)?";

NewPassenger passenger;
cin >> passenger.seat_number;

while (0 < passenger.seat_number && passenger.seat_number <= 100)
{
Airline.seekp((passenger.seat_number - 1 ) * sizeof(NewPassenger));
Airline.read(reinterpret_cast<char *>(&passenger), sizeof(NewPassenger));

cout << " Found Record. Now Enter New Name:";
cin >> passenger.name;

Airline.seekg((passenger.seat_number - 1 ) * sizeof(NewPassenger),ios::beg);
Airline.write(reinterpret_cast<const char *>(&passenger), sizeof(NewPassenger));

cout << "\nEnter Seat Number: ?";
cin >> passenger.seat_number;
}

Airline.close();
cout << endl;

NewPassenger 定义如下:

struct NewPassenger
{
int seat_number;
char name[20];
char onward[3];
};

最佳答案

fstream Airline("AirLine.text", ios::out | ios::in | ios::app | ios::binary);

查看cplusplus.com on fstream::open我看到附加标志描述为

app (append) Set the stream's position indicator to the end of the stream before each output operation.

(强调)。看起来你正在得到你要求的行为。也许你想要

ate (at end) Set the stream's position indicator to the end of the stream on opening.

关于c++ - 附加随机访问文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8285396/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com