1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
|
#include <iostream>
#include <fstream>
#include <istream>
#include <string>
using namespace std;
struct Student
{
int id;
char name[64];
};
int main()
{
Student info;
int r;
ofstream fout("data.txt", ios::binary|ios::app);
cout << "How many student do you want to add? ";
cin >> r;
for (int i=0 ; i<r; i++)
{
cout << "Enter ID: ";
cin >> info.id;
cin.get();
cout << "Enter Name: ";
cin.getline(info.name, 64);
fout.write( (char*)(&info), sizeof(Student) );
fout.flush();
cout<<"\n\n";
}
fout.close();
ifstream fin("data.txt", ios::binary);
Student search_key;
int pos = -1;
cout<<"*****************************************\n\n";
cout<<"Enter ID and name to search: \n";
cin >> search_key.id;
cin.get();
cin.getline(search_key.name, 64);
cout<<"******************************************\n\n";
for (int i=0; !fin.eof() ; i++)
{
fin.read( (char*)(&info), sizeof(Student) );
if ( info.id==search_key.id && strcmp(info.name, search_key.name)==0 )
{
cout << "\tEnter your new id and name:";
cin >> info.id;
cin.get();
cin.getline(info.name, 64);
pos = fin.tellg();
break;
}
fin.peek();
}
fin.close();
if ( pos>=0 )
{
fout.open("data.txt", ios::binary|ios::in);
fout.clear();
fout.seekp( pos-sizeof(Student) );
fout.write( (char*)&info, sizeof(Student) );
fout.close();
}
else
{
cout << "Data not found. . .\n\n";
}
cout<<"******************************************\n\n";
fin.open( "data.txt", ios::binary );
fin.clear();
for (int i=0; !fin.eof() ; i++)
{
fin.read( (char*)(&info), sizeof(Student) );
cout << i+1 << "\t\t" << info.id << "\t\t" << info.name << "\n\n";
fin.peek();
}
fin.close();
return 0;
}
|
First Run
How many student do youw want to add? 3
Enter ID: 9898
Enter Name: bill gates
Enter ID: 7878
Enter Name: steve jobs
Enter ID: 5555
Enter Name: michael jackson
******************************************
Enter ID and name to search:
-1 null
******************************************
Data not found. . .
******************************************
1 9898 bill gates
2 7878 steve jobs
3 5555 michael jackson
Second Run--------------------------------------------
How many student do youw want to add? 1
Enter ID: 7777
Enter Name: bjarne stroustrup
******************************************
Enter ID and name to search:
5555 michael jackson
******************************************
Enter your new id and name:1234 james gosling
******************************************
1 9898 bill gates
2 7878 steve jobs
3 1234 james gosling
4 7777 bjarne stroustrup |