Накалякал примерчик | Код | #include <iostream> #include <fstream> #include <cstring> using namespace std;
const int len = 20; // длинна слов = 20 симолов typedef struct STUDENT{ char name[len]; // имя char family[len]; // фамилия // ... и т.д. struct STUDENT * next;
bool operator>( struct STUDENT * s ){ if( strcmp( family, s->family ) >=0 ) return false; else return true; // сравнение по фамилиям } }Node;
void del( Node *& n ){ // функция удаления списка for( Node * a = n; n; n = a ){ if( a ) a = a->next; delete n; } } /////////////// main /////////////////// int main(int argc, char *argv[]) { Node * begin=NULL, *end, *node; for( int i=0; i<3; i++ ){ // создаем список из 3 студентов node = new Node; cout << "Enter student " << i+1 << " :\n"; cout << "name > "; cin >> node->name; cout << "family > "; cin >> node->family; node->next = NULL; if( !begin ) end = begin = node; else end = end->next = node; }
// сортировка списка по фамилиям if( begin ) for( end = begin, node = begin->next; node; end = node, node=node->next ){ // поиск элемента который больше Node *x, *a; for( a = x = begin; *x > node && x != node; a = x, x=x->next ); if( x == node ) continue; // взяли элемент из списка end->next = node->next; // вставить этот элемет перед большим if( x == begin ){ // в начало begin = node; node->next = a; } else{ // где-то в середину node->next = a->next; a->next = node; } node = end; } // запись в файл fstream file("node.dat", ios::binary| ios::in| ios::out ); if( !file.is_open()) return 1; for( node = begin; node; node = node->next ) file.write( reinterpret_cast<char*>(node), sizeof(Node)); file.flush(); file.clear(); file.seekg(0); file.seekp(0); del( begin ); // удаляем список
// чтение из файла node = new Node; while( !file.read( reinterpret_cast<char*>( node ), sizeof(Node)).eof()){ node->next = NULL; if( !begin ) end = begin = node; else end = end->next = node; node = new Node; } delete node;
if( !begin ){ // если ничего не считали из файла delete node; cout << "Error read file"; cin.sync(); getchar(); return 1; } // вывод считанного из файла списка cout << "\n\nFile student :\n\n"; for( node = begin; node; node=node->next ){ cout << "\nStydent : \n"; cout << "Name = " << node->name << "\n"; cout << "Family = " << node->family << "\n"; } del( begin ); fflush(stdin); getchar(); // пауза return 0; }
|
|