Методические указания ЛР10(примеры)_2014 (1079944), страница 7
Текст из файла (страница 7)
for ( int i =0 ; i< StudCount - 1 ; i++ )
if ( (pStMas + i)->Num > (pStMas + i + 1)->Num ) // Возрастание
SwapStudent( pStMas + i , pStMas + i + 1 );
printf ("Пункт МУ 19 (SORT - pStMas - после Num):\n");
StudPrintMas( pStMas , StudCount);
////////
// МУ п.20
////////
printf ("Пункт МУ 20 (SORT - функция - до):\n");
StudPrintMas( pStMas , StudCount);
StudSortMasNum( pStMas , StudCount );
printf ("Пункт МУ 20 (SORT - функция - после):\n");
StudPrintMas( pStMas , StudCount);
//
////////
// МУ п.21
////////
// Сортировка файла (!!!) по одному полю записи
/////////////////////////////////////////////////////
printf ("Пункт МУ 21 (SORT - c разными функциями):\n");
printf ("СОРТИРОВКА: Работа с функциями Name:\n");
StudSortName("BDStud.bin" );
StudPrintFile( "BDStud.bin" );
/////////////////////////////////////////////////////
printf ("СОРТИРОВКА: Работа с функциями Num (убывание):\n");
StudSortNum("BDStud.bin");
StudPrintFile( "BDStud.bin" );
/////////////////////////////////////////////////////
printf ("СОРТИРОВКА: Работа с функциями Oklad(возрастание ):\n");
StudSortOklad("BDStud.bin" );
StudPrintFile( "BDStud.bin" );
/////////////////////////////////////////////////////
////////
// МУ п.22 чтение одной записи 3-й (0 - 4 )
////////
Student SFind ;
pFBin = _open( "BDStud.bin" , _S_IREAD |_O_BINARY );
if ( pFBin != -1 )
{
long posF = _lseek( pFBin, sizeof(Student) * 2, SEEK_SET ); // Установить новую текущую позицию
int nByte = _read( pFBin , &SFind , sizeof(Student));
};
printf ("Пункт МУ 22:\n");
printf ("Чтение из программы (номер = 3):\n");
PrintStudent( &SFind );
// Закрытие файла
_close( pFBin );
//
////////
// МУ п.22.1 чтение из функции
////////
///// - Прочитать запись по номеру
printf ("Чтение из функции (номер = 1):\n");
// Student SFind ;
FindStudNum( "BDStud.bin" , &SFind , 1);
PrintStudent( &SFind );
////////
// МУ п.22.2 интегрированные расчеты в программе
////////
double SumStip = 0;
Student SIntg;
printf ("Пункт МУ 22.2(Интегральные расчеты):\n");
pFBin = _open( "BDStud.bin" , _S_IREAD |_O_BINARY );
if ( pFBin != -1 )
{
for ( int i = 0 ; _eof(pFBin) == NULL ; i++ )
{
int nByte = _read( pFBin , &SIntg , sizeof(Student));
SumStip = SumStip + SIntg.Oklad;
}
_close( pFBin );
};
printf ( "Фонд зарплаты в цикле = %8.2lf \n" , SumStip );
////////
// МУ п.22
////////
double SumOklad;
printf ( "Фонд зарплаты из функции = %8.2lf \n" , StudSumm( "BDStud.bin" , &SumOklad));
///////////////////////////////////////////////////////
/////////////////////////////////////////////////////
// Очистка файла и его удаление
ClearReadonlyFile("BDStud.bin");
// StudClearFile("BDStud.bin");
// StudRemoveFile("BDStud.bin");
///// УРОВЕНЬ С
///////////////////////////////////////
// МУ п.23
///////////////////////////////////////
////////
// МУ п.23.1
////////
// Добавить запись ( начало )
printf ("Добавление (начало):\n");
Student SFirst = {"Первый" , 22 , 3400.00};
StudAdd("BDStud.bin", SFirst , First );
StudPrintFile( "BDStud.bin" );
////////
// МУ п.23.2
////////
// - Добавить запись ( конец)
printf ("Добавление (конец):\n");
Student SLast = {"Последний" , 22 , 3400.00};
StudAdd("BDStud.bin", SLast );
StudPrintFile( "BDStud.bin" );
/////////////////////////////////////////////////////
////////
// МУ п.23.3
////////
// Добавить запись (номер)
/////////////////////////////////////////////////////
printf ("Добавление (номер):\n");
Student SNumb = {"По номеру - 2" , 33 , 5500.00};
StudAddNum("BDStud.bin", SNumb, 3);
StudPrintFile( "BDStud.bin" );
///// - Удалить запись по номеру (? другие режимы)
/////////////////////////////////////////////////////
////////
// МУ п.23.4
////////printf ("Удаление (Начало):\n");
StudDel("BDStud.bin", First );
StudPrintFile( "BDStud.bin" );
/////////////////////////////////////////////////////
////////
// МУ п.23.5
////////
printf ("Удаление (конец):\n");
StudDel("BDStud.bin", Last );
//StudDel("BDStud.bin" );
StudPrintFile( "BDStud.bin" );
/////////////////////////////////////////////////////
////////
// МУ п.23.6
////////
printf ("Удаление (номер):\n");
StudDelNum("BDStud.bin", 4 );
StudPrintFile( "BDStud.bin" );
/////////////////////////////////////////////////////
////////
// МУ п.23.7
////////
///// - Прочитать запись по номеру
printf ("Чтение (номер):\n");
Student * pFind = new Student;
FindStudNum( "BDStud.bin" , pFind , 2);
PrintStudent( pFind );
/////////////////////////////////////////////////////
// - Изменить запись по номеру
////////
// МУ п.23.8
////////
printf ("Изменение записи (номер):\n");
Student SChang ={"Замена" , 11, 111.00};
ChangeStudNum( "BDStud.bin" , SChang , 2);
StudPrintFile( "BDStud.bin" );
/////////////////////////////////////////////////////
// - Найти запись по признаку раверства поля (имени - первую в файле) по любому полю
////////
// МУ п.23.9
////////
int n;
printf ("Поиск по имени:\n");
if ( ( n =FindStudName( "BDStud.bin" , pFind , "Замена" )) != -1)
{ printf ("Найдена по номеру = %d \n", n );
printf ("Найдена запись: ");
PrintStudent( pFind );
}
else
printf ("Не найдена запись! ");
/////////////////////////////////////////////////////
////////
// МУ п.23.10
////////
// Swap замена записей в файле БД
printf ("Замена SWAP в файле по номеру: 1<->3\n");
SwapStudFile( "BDStud.bin" , 1 ,3 );
StudPrintFile( "BDStud.bin" );
///////////////////////////////////////////////////////
delete [] pStMas;
/////////////////////////////////////////////////////
system("PAUSE");
/////////////////////////////////////////////////////
}
13 Заголовочный файл проекта File_P3.h
File_P3.h– Заголовочный МОДУЛЬ
//
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <io.h>
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <memory.h>
#include <malloc.h>
//
#include <errno.h>
//
//using namespace std;
//////////////////////////////////////
////////
// МУ п.2
////////
struct Student {
public:
char Name[20];
int Num;
double Oklad;
};
// Константы для управления функциями
enum TypeAddDel{ First = 1 , Last = 2 , Default = Last};
// Прототипы
////////
/////////////////////////
// МУ п.5
// Распечатка отдельной структурной переменной студента
////////
void PrintStudent(Student * pS)
{
printf( "Запись: Имя = %-15s Номер = %2d Стипендия = %8.2lf \n",
pS->Name , pS->Num, pS->Oklad );
};
//////////////////////////
// МУ п.8
void StudPrintMas( Student * pMas , int Razm)
{
for (int i = 0 ; i < Razm ; i++ )
{
PrintStudent(pMas + i); // Используется готовая функция
};
};
/////////////////////////////
// Выборка из файла в динамический массив
// МУ п.12
/////////////////////////////
void StudFileToMas( const char * FileName , Student ** pMas , int * pRazm)
{
long posF;
int pFBin = _open( FileName, _S_IREAD |_O_BINARY );
if ( pFBin == -1 ) { *pRazm = NULL; return;};
posF = _lseek( pFBin, 0, SEEK_END ); // Установить новую текущую позицию
*pRazm = posF / sizeof(Student);
//*pMas = new Student[ *pRazm];
*pMas = (Student *) calloc( *pRazm , sizeof(Student) );
posF = _lseek( pFBin, 0, SEEK_SET ); // На начало
// Буфер для чтения
Student SBuf;
for (int i = 0 ; i < *pRazm ; i++ )
{
int nByte = _read( pFBin , &SBuf , sizeof(Student));
if ( nByte == NULL) break;
memcpy( *pMas + i , &SBuf , sizeof(Student));
};
// Закрытие файла
_close( pFBin );
};
//
/////////////////////////////
//Перезапись массива структур в файл (Файл очищается!)
// МУ п.13
///////////////////////////
void StudMasToFile( const char * FileName , Student * pMas , int Razm)
{
char Comand[40];
// Снятие защиты с файла - отключение Readonly
strcpy (Comand , "attrib -R ");
strcat (Comand , FileName);
system( Comand );
int pFBin = _open( FileName , _O_RDWR |_O_BINARY | _O_CREAT | _O_TRUNC);
if ( pFBin == -1 ) return;
// цикл записи
for ( int i = 0 ; i < Razm ; i++ )
{
_write (pFBin , pMas + i , sizeof(Student));
};
_close( pFBin );
//
};
///////////////////////
// Печать файла БД Студентов
// МУ п.14
///////////////////////
void StudPrintFile( const char * FileName )
{
long posF;
int pFBin = _open( FileName, _S_IREAD |_O_BINARY );
if ( pFBin != -1 )
{
posF = _lseek( pFBin, 0, SEEK_END ); // Установить новую текущую позицию
int Razm = posF / sizeof(Student);
if ( Razm == 0 ) { _close( pFBin ); printf( "Записей в файле нет! \n") ; return;};
posF = _lseek( pFBin, 0, SEEK_SET ); // На начало
// Буфер для чтения
Student SBuf;
for (int i = 0 ; i < Razm ; i++ )
{
int nByte = _read( pFBin , &SBuf , sizeof(Student));
if ( nByte == NULL) break;
// вывод записи
printf( "%d - ", i + 1);
PrintStudent(&SBuf);
};
// Закрытие файла
_close( pFBin );
};
};
//////////////////////////////
// Получить число записей в БД
// МУ п.15
int StudFileCount( const char * FileName , int * pRazm)
{
long posF;
int pFBin = _open( FileName, _S_IREAD |_O_BINARY );
if ( pFBin == -1 ) { *pRazm = NULL; return NULL;};
posF = _lseek( pFBin, 0, SEEK_END ); // Установить новую текущую позицию
*pRazm = posF / sizeof(Student);
_close( pFBin );
return *pRazm;
};
/////////////////////////
// Очистка файла студентов
// МУ п.16
/////////////////////////
void StudClearFile(const char * FileName)
{
char Comand[40];
// Временное снятие защиты с файла - отключение Readonly
strcpy (Comand , "attrib -R ");
strcat (Comand , FileName);
system( Comand );
int pFBin = _open( FileName , _O_RDWR |_O_BINARY | _O_CREAT | _O_TRUNC);
if ( pFBin == -1 ) return;
_close( pFBin );
};
//////////////////////////////////
// Сброс флага файла
// МУ п.17
//////////////////////////////////
void ClearReadonlyFile(const char * FileName)
{
char Comand[40];
// Снятие защиты с файла - отключение Readonly
strcpy (Comand , "attrib -R ");
strcat (Comand , FileName);
system( Comand );
};
//////////////////////////////////
// МУ п.18
//////////////////////////////////
// обмен на основе адресов структурных переменных (возможет только без динамики!!)
void SwapStudent ( Student * pA , Student * pB )
{
Student Temp;
/* можно и так
Temp = *pA;
*pA = *pB;















