Методические указания ЛР10(примеры)_2014 (1079944), страница 6
Текст из файла (страница 6)
#include <sys/types.h>
#include <sys/stat.h>
#include <io.h>
//#include <afx.h>
#include <stdio.h>
//#include <iostream>
#include <conio.h>
#include <string>
#include <string.h>
#include <memory.h>
//
#include <errno.h>
//using namespace std;
///
///////////////////////////////////////
// Задание для работы с файлами (уровнь А)
//////////////////////////////////////
// Прототипы функций работы с файлами
// МУ п.5
void PrintStudent(Student * pS);
// МУ п.8
void StudPrintMas( Student * pMas , int Razm);
// МУ п.12
void StudFileToMas( const char * FileName , Student * pMas , int * pRazm);
// МУ п.13
void StudMasToFile( const char * FileName , Student * pMas , int Razm);
// МУ п.14
void StudPrintFile( const char * FileName );
// МУ п.15
int StudFileCount( const char * FileName , int * pRazm);
// МУ п.16
void StudClearFile(const char * FileName);
// МУ п.17
void ClearReadonlyFile(const char * FileName);
// МУ п.18
void SwapStudent ( Student * pA , Student * pB );
// МУ п.20
void StudSortMasNum( Student * pMas , int Razm );
// МУ п.21
void StudSortOklad(const char * FileName );
// МУ п.22
double StudSumm( const char * FileName , double * Sum);
///////////////////////////////////////
// Задание для работы с файлами (уровнь В и С)
//////////////////////////////////////
// МУ п.21
void StudSortName(const char * FileName );
// МУ п.21
void StudSortNum(const char * FileName );
// МУ п.23.1/2
void StudAdd(const char * FileName , Student S , TypeAddDel TAD );
// МУ п.23.4/5
void StudDel(const char * FileName , TypeAddDel TAD );
// МУ п.23.3
void StudAddNum(const char * FileName , Student S , int Numb );
// МУ п.23.6
void StudDelNum(const char * FileName , int Numb );
// МУ п.23.7
void FindStudNum( const char * FileName , Student * pS , int Numb);
// МУ п.23.8
void ChangeStudNum( const char * FileName , Student pS , int Numb);
// МУ п.23.9
int FindStudName( const char * FileName , Student * pS , const char * FindName );
// МУ п.23.10
void SwapStudFile( const char * FileName , int NumA ,int NumB);
// МУ п.17/23ю11
void StudRemoveFile(const char * FileName);
/////////////////////////////////
void main(void)
{
system(" chcp 1251 > nul");
//////////////////////////////////// СИ начало
int pFBin = 0;
/////////////////////////////////////////////////////
//////////////
//StudRemoveFile("BDStud.bin"); // Тестирование БД
////////
// МУ п.3
////////
Student Stud1 ={ "Лаптева" , 1 , 1000.0};
////////
// МУ п.4
////////
Student Stud2;
Stud2.Num = 2;
Stud2.Oklad = 2000.00;
strcpy(Stud2.Name , "Аксенова");
printf ("Пункт МУ 4:\n");
printf( "Stud2: Имя = %-15s Номер = %2d Стипендия = %8.2lf \n\n",
Stud2.Name , Stud2.Num, Stud2.Oklad );
////////
// МУ п.5
////////
printf ("Пункт МУ 5:\n");
PrintStudent(&Stud1) ;
PrintStudent(&Stud2) ;
////////
// МУ п.6
////////
// Student * pStud = new Student;
Student * pStud = (Student *) malloc (sizeof(Student));
pStud->Num = 3;
pStud->Oklad = 3000.00;
strcpy(pStud->Name , "Большаков");
printf ("Пункт МУ 6:\n");
PrintStudent( pStud ) ;
// delete pStud;
free( pStud );
pStud= NULL;
////////
// МУ п.7
////////
Student SMas[] ={{"Первый" , 1 , 1000.0}, {"Второй" , 2 , 2000.0}, {"Третий" , 3 , 3000.0},
{"Четвертый" , 4 , 4000.0}};
int RazmS = sizeof(SMas)/ sizeof(Student); // Вычисление размерности массива
printf ("Пункт МУ 7:\n");
for (int i = 0 ; i < RazmS ; i++ )
PrintStudent( &SMas[i] ) ;
////////
// МУ п.8
////////
printf ("Пункт МУ 8:\n");
StudPrintMas( SMas , RazmS);
////////
// МУ п.9
////////
printf ("Пункт МУ 9:\n");
const int Rzm = 6;
Student * pPotok = new Student[Rzm];
// Заполнение
srand( (unsigned)time( NULL ) ); // Настройка датчика случайных чисел
rand(); // первое число
for (int i=0 ; i < Rzm ; i++ )
{
char Buf[20];
char Num[10];
strcpy(Buf , "Stud № - ");
pPotok[i].Num = (rand()*9)/ RAND_MAX ; // диапазон 0 - 9
pPotok[i].Oklad = 1000.0 * 10.0 * rand() / RAND_MAX ;// диапазон 0 - 10000.0
int n = (rand()*30)/ RAND_MAX ;// диапазон 0 - 30
strcat(Buf , itoa (n + 1 ,Num, 10 ));
strcpy( pPotok[i].Name , Buf);
// PrintStudent( &pPotok[i] );
};
StudPrintMas( pPotok , 6);
////////
// МУ п.10 BDStud.bin
////////
///////
// МУ п.11 Синий
////////
Student ZMas[] ={{"Запись 1" , 0 , 1000.0}, {"Запись 2" , 0 , 2000.0}, {"Запись 3" , 0 , 3000.0},
{"Запись 4" , 0 , 4000.0}};
int RazmZ = sizeof(ZMas)/ sizeof(Student); // Вычисление размерности массива
printf ("Пункт МУ 11(синий):\n");
system ( "attrib -R BDStud.bin "); // Снятие атрибута защиты записи, нужно после первого создания
pFBin = _open( "BDStud.bin", _O_RDWR |_O_BINARY | _O_CREAT | _O_TRUNC);
system("attrib -R BDStud.bin ");
if ( pFBin != -1 )
{
for ( int i = 0 ; i < RazmZ ; i++ )
{
ZMas[i].Num = i + 1;
_write (pFBin , &ZMas[i] , sizeof(Student));
};
_close( pFBin );
};
StudPrintMas( ZMas , RazmZ);
system("attrib -R BDStud.bin ");
////////
// МУ п.11 Рас
Student MASStud[100];
Student SRBuf;
printf ("Пункт МУ 11(Печать файла):\n");
pFBin = _open( "BDStud.bin", _O_RDWR |_O_BINARY );
if ( pFBin != -1 )
{
for ( int i = 0 ; _eof(pFBin) == NULL ; i++ )
{
/* int nByte = _read( pFBin , &SRBuf , sizeof(Student));
PrintStudent( &SRBuf ); */
int nByte = _read( pFBin , &MASStud[i] , sizeof(Student));
PrintStudent( &MASStud[i] );
RazmZ = i;
}
_close( pFBin );
};
printf ("Пункт МУ 11(Печать всего массива):\n");
StudPrintMas( MASStud , RazmZ + 1 );
////////
// МУ п.11 Зеленый
////////
printf ("Пункт МУ 11:\n");
system ( "attrib -R BDStud.bin "); // Снятие атрибута защиты записи, нужно после первого создания
pFBin = _open( "BDStud.bin", _O_RDWR |_O_BINARY | _O_CREAT | _O_TRUNC);
system("attrib -R BDStud.bin ");
if ( pFBin != -1 )
{
for ( int i = 0 ; i < 4 ; i++ )
{
Student StudFile;
char Buf[20];
char Num[10];
strcpy(Buf , "Запись № - ");
StudFile.Num = (rand()*9)/ RAND_MAX ;
StudFile.Oklad = 1000.0 * 10.0 * rand() / RAND_MAX ;
strcat(Buf , itoa (i + 1 ,Num, 10 ));
strcpy( StudFile.Name , Buf);
//
_write (pFBin , &StudFile , sizeof(Student));
PrintStudent( &StudFile );
};
//
_close( pFBin );
system("attrib -R BDStud.bin ");
};
// Специальные функции:
// - из файла в массив ( имя файла , указатель на массив структурных переменных)
/////////////////////////////////////////////////////
////////
// МУ п.12
////////
Student * pStMas;
int StudCount;
//
printf ("Пункт МУ 12:\n");
//printf ("Работа с функциями:\n");
StudFileToMas( "BDStud.bin" , &pStMas , &StudCount );
StudPrintMas( pStMas , StudCount);
// - из массива в файл ( имя файла , указатель на массив структурных переменных)
strcpy( (char *)((pStMas + 1)->Name) , "Новая");
/////////////////////////////////////////////////////
////////
// МУ п.13
////////
Student NZMas[] ={{"Запись 1" , 1 , 1000.0}, {"Запись 2" , 2 , 5000.0}, {"Запись 3" , 3 , 3000.0},
{"Запись 4" , 4 , 4000.0}};
RazmZ = sizeof(NZMas)/ sizeof(Student); // Вычисление размерности массива
// Изменение второй (индекс = 1) записи
NZMas[1].Num =5;
strcpy( NZMas[1].Name , "Изменение 2-й");
printf ("Пункт МУ 13:\n");
StudMasToFile( "BDStud.bin" , NZMas , RazmZ );
printf ("После редактирования массива и запоминания в файле\n");
StudPrintMas( NZMas , StudCount);
////////
// МУ п.14
////////
printf ("Пункт МУ 14:\n");
printf ("После редактирования массива и запоминания - распечатка из файла функцией:\n");
// Распечатка файла записей
StudPrintFile( "BDStud.bin" );
// Число записей в БД
////////
// МУ п.15
////////
printf ("Пункт МУ 15:\n");
/////////////////////////////////////////////////////
printf( "Число записей в БД = %d \n",StudFileCount( "BDStud.bin" , &StudCount ));
// Заполнение файла на основе массива
////////
// МУ п.13 (второй вариант на основе инициализированного массива)
////////
printf ("Пункт МУ 13:\n");
Student StudMas[] ={{"Иванов" , 3 , 7000.0}, {"Петров" , 2 , 2000.0}, {"Сидоров" , 1 , 3000.0}, {"Печкин" , 4 , 4000.0}};
StudMasToFile( "BDStud.bin" , StudMas , StudCount );
// Распечатка файла записей
StudPrintFile( "BDStud.bin" );
//
////////
// МУ п.16
////////
printf ("Пункт МУ 16:\n");
StudClearFile("BDStud.bin");
StudPrintFile( "BDStud.bin" );
////////
// МУ п.17
////////
//
printf ("Пункт МУ 17:\n");
// StudRemoveFile("BDStud.bin"); // Временно за комментировано
ClearReadonlyFile("BDStud.bin");
StudClearFile("BDStud.bin");
StudPrintFile( "BDStud.bin" );
//
printf ("Пункт МУ 17 снова добавим записи из массива:\n");
StudMasToFile( "BDStud.bin" , pStMas , StudCount );
StudPrintFile( "BDStud.bin" );
////////
// МУ п.18
////////
printf ("Пункт МУ 18 (Sawp - до):\n");
Student StudA ={ "Лаптева" , 1 , 1000.0};
Student StudB ={ "Иванова" , 2 , 2000.0};
PrintStudent(&StudA) ;
PrintStudent(&StudB) ;
printf ("Пункт МУ 18 (Sawp - после):\n");
SwapStudent( &StudA , &StudB); // Обмен двух отдельныз записей
PrintStudent(&StudA) ;
PrintStudent(&StudB) ;
// В массиве
printf ("Пункт МУ 18 (Sawp - pStMas - до):\n");
StudPrintMas( pStMas , StudCount);
printf ("Пункт МУ 18 (Sawp - pStMas - после):\n");
SwapStudent( &pStMas[0] , &pStMas[2]); // Обмен двух элементов массива
StudPrintMas( pStMas , StudCount);
// Сортировка массива по одному полю записи
////////
// МУ п.19
////////
printf ("Пункт МУ 19 (SORT - pStMas - до):\n");
StudPrintMas( pStMas , StudCount);
// Сортировка по окладу
for( int k =0 ; k< StudCount - 1 ; k++)
for ( int i =0 ; i< StudCount - 1 ; i++ )
if ( (pStMas + i)->Oklad > (pStMas + i + 1)->Oklad ) // Возрастание
SwapStudent( pStMas + i , pStMas + i + 1 );
printf ("Пункт МУ 19 (SORT - pStMas - после Oklad):\n");
StudPrintMas( pStMas , StudCount);
// Сортировка по имени
for( int k =0 ; k< StudCount - 1 ; k++)
for ( int i =0 ; i< StudCount - 1 ; i++ )
if ( strcmp((pStMas + i)->Name , (pStMas + i + 1)->Name ) > 0 ) // Возрастание
SwapStudent( pStMas + i , pStMas + i + 1 );
printf ("Пункт МУ 19 (SORT - pStMas - после Name):\n");
StudPrintMas( pStMas , StudCount);
// Сортировка по номеру
for( int k =0 ; k< StudCount - 1 ; k++)














