Консультация № 137628
20.05.2008, 14:48
0.00 руб.
0 1 1
Уважаемые эксперты, помогите пожалуйста разобраться в программке.
Необходимо разработать программу добавления информации в произвольное место бинарного файла. Вроде добавляется, но в конец файла, а хотелось бы, чтобы в позицию, которую указывает пользователь. В приложении то, что у меня получилось.

Приложение:
#include<iostream>#include<fstream>using namespace std;class person { char name[80]; int age;public: void getdata() { cout<<"Vvedite imya: "; cin>>name; cout<<"Vvedite vozrast: "; cin>>age; cout<<endl; cout<<"soderjomoe faila: "; cout<<endl; cout<<endl; } void showdata() { cout<<"Imya: "<<name<<endl; cout<<"Vozrast: "<<age<<endl; cout<<endl; }};int main(){ person pr; ofstream outfile; outfile.open("person.bin", ios::app|ios::binary); outfile.seekp(0, ios::end); int endposition=outfile.tellp(); int n=endposition/sizeof(pr); cout<<" V faile "<<n<<" chelovek(a)"<<endl; cout<<"vvedite nomer pozicii, v kotoruy budet zapisan chelovek: "; cin>>n; int position=(n-1)*sizeof(person); outfile.seekp(position); pr.getdata(); outfile.write(reinterpret_cast<char*>(&pr), sizeof(pr)); ifstream infile("person.bin", ios::binary); infile.read(reinterpret_cast<char*>(&pr), sizeof(pr)); while (!infile.eof()) { pr.showdata(); infile.read(reinterpret_cast<char*>(&pr), sizeof(pr)); } getchar(); return 0;}

Обсуждение

Неизвестный
20.05.2008, 15:59
общий
это ответ
Здравствуйте, Белозерцева Ольга!

Если пишете и читаете из файла откройте поток как:
fstream in("person.bin",ios::in|ios::out|ios::binary);
Запись в файл:
cout << " Enter number to change ";
cin >>num;
if(--num >= 0)
{
cout << " Enter struct elements. \n";
in.seekp(num*sizeof(person),ios::beg); //указываем позицию для записи
char t[l_name+1];
cout << "\n Name : ";
cin>>t;
strcpy(st.name,t);
cout<< "\n Age : ";
cin>>st.age;
in.write((char *)&st,sizeof(person)); //запись в файл
}




Форма ответа