0% found this document useful (0 votes)
186 views

C Project Code

The document describes a C program for managing employee records using structures and file handling. It includes functions for adding, viewing, modifying and deleting employee records from a binary file. The main menu allows the user to choose these options and call the respective functions to manage the records.

Uploaded by

badhonctg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
186 views

C Project Code

The document describes a C program for managing employee records using structures and file handling. It includes functions for adding, viewing, modifying and deleting employee records from a binary file. The main menu allows the user to choose these options and call the respective functions to manage the records.

Uploaded by

badhonctg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 63

#include <stdio.

h> ///for input output functions like printf, scanf


#include <stdlib.h>
#include <conio.h>
#include <windows.h> ///for windows related functions (not important)
#include <string.h> ///string operations

/** List of Global Variable */


COORD coord = {0,0}; /// top-left corner of window

/**
function : gotoxy
@param input: x and y coordinates
@param output: moves the cursor in specified position of console
*/
void gotoxy(int x,int y)
{
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);
}

/** Main function started */

int main()
{
FILE *fp, *ft; /// file pointers
char another, choice;

/** structure that represent a employee */


struct emp
{
char name[40]; ///name of employee
int age; /// age of employee
float bs; /// basic salary of employee
};

struct emp e; /// structure variable creation

char empname[40]; /// string to store name of the employee

long int recsize; /// size of each record of employee

/** open the file in binary read and write mode


* if the file EMP.DAT already exists then it open that file in read write mode
* if the file doesn't exit it simply create a new copy
*/
fp = fopen("EMP.DAT","rb+");
if(fp == NULL)
{
fp = fopen("EMP.DAT","wb+");
if(fp == NULL)
{
printf("Connot open file");
exit(1);
}
}

/// sizeo of each record i.e. size of structure variable e


recsize = sizeof(e);

/// infinite loop continues untile the break statement encounter


while(1)
{
system("cls"); ///clear the console window
gotoxy(30,10); /// move the cursor to postion 30, 10 from top-left corner
printf("1. Add Record"); /// option for add record
gotoxy(30,12);
printf("2. List Records"); /// option for showing existing record
gotoxy(30,14);
printf("3. Modify Records"); /// option for editing record
gotoxy(30,16);
printf("4. Delete Records"); /// option for deleting record
gotoxy(30,18);
printf("5. Exit"); /// exit from the program
gotoxy(30,20);
printf("Your Choice: "); /// enter the choice 1, 2, 3, 4, 5
fflush(stdin); /// flush the input buffer
choice = getche(); /// get the input from keyboard
switch(choice)
{
case '1': /// if user press 1
system("cls");
fseek(fp,0,SEEK_END); /// search the file and move cursor to end of the file
/// here 0 indicates moving 0 distance from the end of the file

another = 'y';
while(another == 'y') /// if user want to add another record
{
printf("\nEnter name: ");
scanf("%s",e.name);
printf("\nEnter age: ");
scanf("%d", &e.age);
printf("\nEnter basic salary: ");
scanf("%f", &e.bs);

fwrite(&e,recsize,1,fp); /// write the record in the file


printf("\nAdd another record(y/n) ");
fflush(stdin);
another = getche();
}
break;
case '2':
system("cls");
rewind(fp); ///this moves file cursor to start of the file
while(fread(&e,recsize,1,fp)==1) /// read the file and fetch the record one record per fetch
{
printf("\n%s %d %.2f",e.name,e.age,e.bs); /// print the name, age and basic salary
}
getch();
break;

case '3': /// if user press 3 then do editing existing record


system("cls");
another = 'y';
while(another == 'y')
{
printf("Enter the employee name to modify: ");
scanf("%s", empname);
rewind(fp);
while(fread(&e,recsize,1,fp)==1) /// fetch all record from file
{
if(strcmp(e.name,empname) == 0) ///if entered name matches with that in file
{
printf("\nEnter new name,age and bs: ");
scanf("%s%d%f",e.name,&e.age,&e.bs);
fseek(fp,-recsize,SEEK_CUR); /// move the cursor 1 step back from current position
fwrite(&e,recsize,1,fp); /// override the record
break;
}
}
printf("\nModify another record(y/n)");
fflush(stdin);
another = getche();
}
break;
case '4':
system("cls");
another = 'y';
while(another == 'y')
{
printf("\nEnter name of employee to delete: ");
scanf("%s",empname);
ft = fopen("Temp.dat","wb"); /// create a intermediate file for temporary storage
rewind(fp); /// move record to starting of file
while(fread(&e,recsize,1,fp) == 1) /// read all records from file
{
if(strcmp(e.name,empname) != 0) /// if the entered record match
{
fwrite(&e,recsize,1,ft); /// move all records except the one that is to be deleted to temp file
}
}
fclose(fp);
fclose(ft);
remove("EMP.DAT"); /// remove the orginal file
rename("Temp.dat","EMP.DAT"); /// rename the temp file to original file name
fp = fopen("EMP.DAT", "rb+");
printf("Delete another record(y/n)");
fflush(stdin);
another = getche();
}
break;
case '5':
fclose(fp); /// close the file
exit(0); /// exit from the program
}
}
return 0;
}
Cyber Management System
Client site:
Config.h -----file

/*
File:- config.h
Desc:- contains all the variable declarations,functions declarations,constans definition...
*/

#include <stdio.h> //Provides the core input and output capabilities of the C language.
#include <conio.h> //for doing console input output
#include <ctype.h> //Contains functions used to classify characters by their types or to convert between
upper and lower case in a way that is independent of the used character set
#include <stdlib.h> //For performing a variety of operations, including conversion, pseudo-random
numbers, memory allocation, process control, environment, signalling, searching, and sorting.
#define _WIN32_WINNT 0x0500 //constant for console resizing (redifinition)
#include <windows.h> //defines a very large number of Windows specific functions that can be used in
C.
#include <string.h> //For manipulating several kinds of strings.
#include <time.h> //For converting between various time and date formats.
#include <winsock2.h> // contains functions for socket programmming
#include <process.h> //contains functions for threading process.
#define DEFAULT_PORT 5000
#define STRLEN 256
#define NUM_CLIENTS 2
#define ESC 27
#define F2 60

FILE *ip;

int port_add ; //default


char ipaddress[50];
int no_of_clients = 0; //counter for number of clients being connected
char recMessage[STRLEN];
char sendMessage[STRLEN];
char *client_ip_address;

//variables to be sent to the server

int computer_id=5;
int service_id=0;;
int log_stat=0;
bool is_member=0; // to see if the current customer is a member or not 1 means member, 2 means
admin, 0 means guest
char username[20];
char password[20];
int tot_cost=0;
char CyberName[20];
int fixed_rate;
int tot_service;
int cost_changed=0;
int check_flag = 0;
//Input and Output Handles

HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);


HANDLE hIn = GetStdHandle(STD_INPUT_HANDLE);
HANDLE time_thread;

//for maximizing window


extern "C" WINBASEAPI HWND WINAPI GetConsoleWindow (void);

SOCKET Socket;
struct client
{
sockaddr_in c_address;
int c_addr_len;
SOCKET c_socket;
bool connected;
bool turn;
};
struct client c[NUM_CLIENTS]; //struct client c[n]; if multiple clients

struct service {
char name[15];
int rate;
}items[10];

struct ip_info
{
char ip_address[50];
int port_no;
int client_no;
};
struct ip_info ip1;

COORD coord = {0, 0}; // sets coordinates to 0,0


COORD max_buffer_size = GetLargestConsoleWindowSize(hOut);
COORD max_res,cursor_size;

bool SOCKET_START = false; //TRUE if socket is already initialised


bool login_server = false; // TRUE if server is alerady logged in
bool done = false; //if it is true, the communication ends

time_t t; // structure for accessing system time

//Global variables
int i,j,k;

int flag_menu=0; //flag for menu


int to_tray = 0; //to check if the user wants to go back to tray mode
//Interface Function declarations
void main_menu(); //Main interface of the system

//Utility functions
void gotoxy(int x,int y); //jump to coordinates
void delay(unsigned int mseconds); //create a delay
void console_resize(int console_id);
void reset_console();
void login_screen();
void admin_page();
void show_menu();
void service_menu();
void settings_menu();
void order(int ord);
void chg_compID();
void chg_password();
void credits();
void log_out();
void help_window();
void console_settings();
void reset_variables();

//Server client related functions


void start_socket();
void connect_server();
void cl_send_data(char* menu_selected, char* log_status);
int cl_recv_data();
int get_code();
//thread functions
void show_time(void *param);
void update_price(void *param);

void readMessage(int msgExtracted[4],char msg[STRLEN]);


void intToString(int n, char str[]);
void get_password(char* pass);
bool confirm_member();
char* createMessage(char Message[]);
int get_service_info(); //returns the size of the array

HWND WINAPI GetConsoleWindowNT();


Function.h--------file

/*
File:- function.h
Desc:- contains all the functions related to menu control,server and client interfacing
*/
#include "config.h"
#include "sock.h"
#include "interface.h"

void show_time(void *param) {


long i = 0; /* Loop counter */
/* Holds initial clock time */
int interval = 1; /* Seconds interval for o/p */
int elapsed = 0;
int min=0,MIN=0,hrs=0,sec=0;
int d=0,f=0;
//now = clock(); /* Get current clock time */
int pos=2;

for(i = 0 ; ; i++)
{
// if(log_stat==0) {break;}
//elapsed = (clock()-now)/CLOCKS_PER_SEC;

if(i%60==0)
{

min=i/60;
d=60*min;
if(min%60==0)
{
hrs=min/60;
f=60*hrs;
}
}
sec=i-d;
MIN=min-f;
if(hrs<10)
{
gotoxy(7,pos);printf("0%d",hrs);
}
else
{
gotoxy(7,pos);printf(":%d",hrs);
}
if(min<10)
{
gotoxy(9,pos);printf(":0%d",MIN);
}
else
{
gotoxy(9,pos);printf(":%2d",MIN);
}

if(sec<10)
{
gotoxy(12,pos);printf(":0%d",sec);
}
else
{
gotoxy(12,pos);printf(":%2d",sec);
}
if(MIN==0 && sec == 2) {
cost_changed = fixed_rate/4;
} else if(MIN ==15 && sec == 0) {
cost_changed = fixed_rate/4;
} else if(MIN == 30 && sec == 0) {
cost_changed = fixed_rate/2;
}

if (log_stat==2) {break;}
if(cost_changed != 0) {
tot_cost += cost_changed;
}
cost_changed = 0;
gotoxy(28,2);printf("Rs.%d",tot_cost);
delay(1000);
}
_endthread();
}

void delay(unsigned int mseconds)


{
clock_t goal = mseconds + clock();
while (goal > clock());
}

int get_code(void)
{
char key;
if((key=getch())==0)
return(getch());
else if(key=='\r')
return(key);
else if(key==ESC)
return(key);
else if(key==getch())
return (key);
else
return (0);

} //end of get_code()

void intToString(int n, char str[])


{
int i = 0; /* Loop counter */
int negative = 0; /* Indicate negative integer */
int temp = 0; /* Temporary storage */

if(negative = (n<0)) /* Is it negative? */


n = -n; /* make it positive */

/* Generate digit characters in reverse order */


do
{
str[i++] = '0'+n%10; /* Create a rightmost digit */
n /= 10; /* Remove the digit */
}while(n>0); /* Go again if there's more digits */

if(negative) /* If it was negative */


str[i++] = '-'; /* Append minus */
str[i] = '\0'; /* Append terminator */

str = strrev(str); //reverse the string


/* Return the string */
}

//this function resets all the variables to null before sending!!


void reset_variables() {
service_id = 0;
is_member = 0;
strcpy(username,"");
strcpy(password,"");
fixed_rate;
tot_service;
cost_changed=0;
check_flag = 0;
tot_cost=0;
to_tray = 1;
}

void get_password(char* pass)


{
char temp_passP[25];
int i=0;
while(1)
{
temp_passP[i]=getch();
if(temp_passP[i]==13){break;}
else if(temp_passP[i]==8)
{
if(i!=0) {
printf("\b \b");
i--;
} else {printf("\a");}
}
else
{
printf("*");
*(pass+i) = temp_passP[i];
i++;
}
*(pass+i)='\0';
}
}

bool confirm_member() {
char Message[STRLEN],repMessage[STRLEN];
createMessage(Message);
c_send_data(Message);
c_recv_data(repMessage);
if(repMessage[0] == '1') {
for(i=2;repMessage[i]!=':';i++) {
CyberName[i-2] = repMessage[i];
}
CyberName[i-1] = '/0';
i++; char x[4];
for(j=i;repMessage[j]!=':';j++) {
x[j-i] = repMessage[j];
}
x[j-i-1] = '/0';
fixed_rate = atoi(x);
return true;
} else { return false;}

char* createMessage(char Message[]) {


char a[3],b[3],c[3],cost[6];
intToString(computer_id,Message);
intToString(service_id,a);
intToString(log_stat,b);
intToString(is_member,c);
//printf(":::%s-%d-%s:::",a,log_stat,c);

//creating message to be sent


strcat(Message,":");
if (atoi(a) == 2){
intToString(tot_cost,cost);
strcat(Message,cost);
} else {
strcat(Message,a);
}
strcat(Message,":");
strcat(Message,b);
strcat(Message,":");
strcat(Message,c);
strcat(Message,":");
if (!strcmp(username,"")) {
strcat(Message,"0");
} else {strcat(Message,username);}
strcat(Message,":");
if (!strcmp(password,"")) {
strcat(Message,"0");
} else {strcat(Message,password);}
strcat(Message,":");

// printf("\n%s",Message);getch();
//creating message to be sent
return Message;
}

int get_service_info() {
char Message[STRLEN],repMessage[STRLEN],item[15],rate[4];
log_stat = 3;
createMessage(Message);
c_send_data(Message);
int a = 0;
while(1) {
c_recv_data(repMessage);
for(i=0;repMessage[i]!=':';i++) {
item[i] = repMessage[i];
}
item[i]='\0';
i++;
strcpy(items[a].name,item);

for(j=i;repMessage[j]!=':';j++) {
rate[j-i] = repMessage[j];
}
rate[j] = '\0';
j++;
items[a].rate = atoi(rate);

char tmp_flag = repMessage[j];


int flag = atoi(&tmp_flag);
//printf("%s",items[a].name);getch();
if(flag) { break;}
a++;
strcpy(item,"");
}
return (a+1); //returns the size of the array

void assign_ip_address(void)

FILE *assignIp;
assignIp=fopen("ip_add.dat","rb");
if(ip==NULL)
{
printf("\nCan not open file");
exit(1);
}
while(fread(&ip1,sizeof(ip1),1,assignIp)==1)
{
strcpy(ipaddress,ip1.ip_address);
port_add=ip1.port_no;
computer_id = ip1.client_no;
}
fclose(assignIp);
}

interface.h-------file

HWND WINAPI GetConsoleWindowNT()


{
// declare function pointer type

typedef HWND WINAPI (*GetConsoleWindowT)(void);

// declare one such function pointer

GetConsoleWindowT GetConsoleWindow;

// get a handle on kernel32.dll

HMODULE hK32Lib = GetModuleHandle(TEXT("KERNEL32.DLL"));

// assign procedure address to function pointer

GetConsoleWindow = (GetConsoleWindowT)GetProcAddress(hK32Lib,TEXT("GetConsoleWindow"));

// check if the function pointer is valid

// since the function is undocumented


if ( GetConsoleWindow == NULL ) {
return NULL;
}

// call the undocumented function

return GetConsoleWindow();

}
//Interface Layout
void window(void)
{
int i;
int down=18,left=51,right=131;
for(i=left;i<=81;i++)
{
gotoxy(i,down);printf("\xB2");
}
for(i=101;i<=right;i++)
{
gotoxy(i,down);printf("\xB2");
}
for(i=down;i<=left-3;i++)
{
gotoxy(left,i);printf("\xB2");
}
for(i=left;i<=right;i++)
{
gotoxy(i,left-3);printf("\xB2");
}
for(i=down;i<=left-3;i++)
{
gotoxy(right,i);printf("\xB2");
}
gotoxy(right-8,left-4);printf("C. YBER");
//gotoxy(left+2,left-4);printf("Back : ESC");
}

void login_screen() {
int mid=85,down=18;
console_resize(3);

system("cls");
window();
gotoxy(mid,down);printf("Log In Screen\n");
gotoxy(mid,down+2);printf("C.yber Client\n");
gotoxy(mid,down+4);printf("Cyber XYZ\n");
gotoxy(mid-5,down+7);printf("1. Sign in as Member\n");
gotoxy(mid-5,down+10);printf("2. Sign in as Guest\n");

gotoxy(58,35);printf("Select an option:: ::");


char sel;
while(1) {
sel = getch();
if (sel == '1' || sel == '2') {
break;
}

}
switch (sel) {
case '1':
while(1) {
system("cls");
window();
gotoxy(mid,down); printf("Member Sign In");
gotoxy(mid,down+2);printf("Username::\t");gets(username);
gotoxy(mid,down+4);printf("Password::\t");get_password(password);
//action to check username and password
is_member = 1;

if(confirm_member()) {
break;
} else {
MessageBox(0,"Invalid Username Or Password:: Please Try Again!","Error",0);
strcpy(username,"");
strcpy(password,"");
log_stat = 0;
}
}
break;
case '2':
char Message[STRLEN], repMessage[STRLEN];
is_member = 0;
createMessage(Message);
c_send_data(Message);
c_recv_data(repMessage);
for(i=2;repMessage[i]!=':';i++) {
CyberName[i-2] = repMessage[i];
}
CyberName[i-1] = '/0';
i++; char x[4];
for(j=i;repMessage[j]!=':';j++) {
x[j-i] = repMessage[j];
}
x[j-i-1] = '/0';
fixed_rate = atoi(x);
break;
}
tot_service = get_service_info();
log_stat = 1;
//continue to tray
}

void main_menu(){ //main menu


console_resize(1);
//move_window();
system("cls");
printf("** Welcome To %s **\n\n\n\n\n",CyberName);
printf("Press F2 to see menu.");
gotoxy(0,2);printf("Timer:\t\t Price:");
}

void gotoxy (int x, int y)


{
coord.X = x; coord.Y = y; // X and Y coordinates
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}

void reset_console() {
CONSOLE_SCREEN_BUFFER_INFO SBInfo;
HWND hWnd = GetConsoleWindowNT();
COORD NewSBSize;

int Status;
/* Resetting the console size and buffer */
NewSBSize.X = 13;
NewSBSize.Y = 2;

Status = MoveWindow(hWnd,0,0,50,50,TRUE);

if (Status == 0)
{
printf("Failed:: reset console size");
}

Status = SetConsoleScreenBufferSize(hOut, NewSBSize);


if (Status == 0)
{
printf("Failed:: reset console buffer");
}
}

void console_resize(int console_id) {


reset_console();
DWORD max_resX = GetSystemMetrics(SM_CXSCREEN);
DWORD max_resY = GetSystemMetrics(SM_CYSCREEN);
CONSOLE_SCREEN_BUFFER_INFO SBInfo;
HWND hWnd = GetConsoleWindowNT();
COORD NewSBSize;
int Status,L,T,R,B;

if (console_id == 1) {
NewSBSize.X = 35;
NewSBSize.Y = 7;
T = max_resY-150;
B = 150;
L = max_resX-300;
R = 300;

} else
if (console_id == 2) {
NewSBSize.X = 35;
NewSBSize.Y = 45;
T = max_resY-600;
B = 600;
L = max_resX-300;
R = 300;
} else if (console_id == 3) {
NewSBSize.X = max_resX/8;
NewSBSize.Y = max_resY/12;
T = 0;
L = 0;
R = max_resX;
B = max_resY;
}

Status = SetConsoleScreenBufferSize(hOut, NewSBSize);


if (Status == 0)
{
printf("Failed:: resize console size");
}

Status = MoveWindow(hWnd,L,T,R,B,TRUE);
if (Status == 0)
{
printf("Failed:: resize console size");
}
//printf("%d,%d,%d,%d--%d,%d",L,T,R,B,NewSBSize.X,NewSBSize.Y); getch();
}

void show_menu() {
flag_menu=0;
console_resize(2);
system("cls");
gotoxy(10,4); printf("%s Menu",CyberName);
gotoxy(10,8);printf("1. Order Service");
gotoxy(10,10);printf("2. Credits");
gotoxy(10,12);printf("3. Log Out");
gotoxy(0,2);printf("Timer:\t\t Price: ");
//gotoxy(5,18);printf("Press Esc to go back to default console");
gotoxy(0,16); printf("Select an Item::");
gotoxy(0,20);printf("ESC -> Back\tT -> Tray Console\nH -> Help");
}

void service_menu() {
flag_menu=1;
system("cls");
printf("C.yber-Client");
gotoxy(10,4); printf("%s Service Menu",CyberName);
gotoxy(5,8);printf("Item Name");
gotoxy(20,8);printf("Rate(Rs.)");

for ( i = 0; i<=tot_service-1; i++) {


gotoxy(5,10+i); printf("%d. %s",i+1,items[i].name);
gotoxy(25,10+i); printf("%d",items[i].rate);
}

gotoxy(0,2);printf("Timer:\t\t Price: ");


//gotoxy(5,18);printf("Press Esc to go back to default console");
gotoxy(0,tot_service+14); printf("Select an Item::");
gotoxy(0,tot_service+18);printf("T -> Tray Console\tESC -> Back\nH -> Help");
int breakLoopFlag = 0;
while(1) {
char sel = tolower(getch());
if (sel == 't') {
to_tray = 1;
breakLoopFlag = 1;
} else
if(sel == 27) {
to_tray = 4;
breakLoopFlag = 1;
} else
if(sel == 'h') {
to_tray = 3;
breakLoopFlag = 1;
} else {
int serv_id = atoi(&sel);
for(i=1;i<=tot_service;i++) {
if(serv_id == i) {
char Message[STRLEN],repMessage[1];
service_id = serv_id;
cost_changed = items[service_id-1].rate;
createMessage(Message);
c_send_data(Message);
c_recv_data(repMessage);
service_id = 0;
if(repMessage[0]=='1') {
MessageBox(0,"Your Order Will Be Delivered Soon","Service Message",0);
to_tray = 4; breakLoopFlag = 1; break;
} else if (repMessage[0] = '0'){
MessageBox(0,"Sorry! We are out of that...","Service Message",0);
to_tray = 4; breakLoopFlag = 1; break;
}
}
}
}
if(breakLoopFlag) {break;} //condition to end the infinite loop
}

void settings_menu() {
flag_menu=2;

//Requesting Server for informations on services

char buffer[STRLEN],a[3],b[2];
intToString(computer_id,a);
intToString(is_member,b);
strcat(buffer,a);strcat(buffer,":");
strcat(buffer,"0");strcat(buffer,":"); //service_id
strcat(buffer,"3");strcat(buffer,":"); //log_stat
strcat(buffer,b);strcat(buffer,":");
c_send_data(buffer);

//Requesting Server for informations on services


//accepting service informations and printing the menu
char recMessage[STRLEN];
c_recv_data(recMessage);
int msgExtracted[4];
// readMessage(msgExtracted,recMessage);

system("cls");
printf("C.yber-Client");
gotoxy(10,4); printf("Cyber XYZ Settings");
gotoxy(10,8);printf("1. Change Computer ID");
gotoxy(10,10);printf("2. Change Password");
gotoxy(10,12);printf("3. Change Server IP");
gotoxy(0,2);printf("Timer:\t\t Price: ");
//gotoxy(5,18);printf("Press Esc to go back to default console");
gotoxy(0,16); printf("Select an Item::");
gotoxy(0,20);printf("T -> Tray Console\tESC -> Back\nH -> Help");
//accepting service informations and printing the menu
}

void credits() {
flag_menu=3;
system("cls");
printf("C.yber-Client");
gotoxy(10,4); printf("CODDED BY");
gotoxy(8,5);printf("-----------------");
gotoxy(10,6);printf("<BASE 2 />");
gotoxy(6,8);printf("1. Aayush Shrestha");
gotoxy(6,9);printf("2. Ashok Basnet");
gotoxy(6,10);printf("3. Bibek Subedi");
gotoxy(6,11);printf("4. Dinesh Subedi");
gotoxy(2,12);printf("066 BCT , IOE pulchowk campus");
gotoxy(2, 14);printf("No copyright (C) protected: ");
gotoxy(2,16);printf("We love open source");
gotoxy(0,2);printf("Timer:\t\t Price: ");
gotoxy(0,20);printf("T -> Tray Console\tESC -> Back\nH -> Help");
to_tray = 0;
}

void log_out() {
console_resize(1);
log_stat = 2; // 2 means logging out status
service_id = tot_cost;
char Message[STRLEN];
createMessage(Message);
c_send_data(Message);
system("cls");
printf("Logging out");
for(i=0;i<=5;i++) {
delay(300);
printf(".");

}
reset_variables();
}

void help_window() {
flag_menu=9;
system("cls");
gotoxy(2,4);printf("HELP File");
gotoxy(1,5);printf("-------------------------");
gotoxy(2,7);printf("F2 -> To maximize the size of");
gotoxy(2,8);printf(" Console");
gotoxy(2,9);printf("T -> To minimize the size of ");
gotoxy(2,10);printf(" Console");
gotoxy(2,11);printf("H -> For Help");
gotoxy(2,12);printf("Esc -> For back");
gotoxy(0,2);printf("Timer:\t\t Price: ");
gotoxy(0,20);printf("T -> Tray Console\tESC -> Back\nH -> Help");
}

void console_settings() {
EnableMenuItem(GetSystemMenu(GetConsoleWindow(), FALSE), SC_CLOSE , MF_GRAYED);
RemoveMenu(GetSystemMenu(GetConsoleWindow(), FALSE), SC_CLOSE , MF_GRAYED);
RemoveMenu(GetSystemMenu(GetConsoleWindow(), FALSE), SC_MINIMIZE , MF_BYCOMMAND);
RemoveMenu(GetSystemMenu(GetConsoleWindow(), FALSE), SC_SIZE , MF_BYPOSITION);
RemoveMenu(GetSystemMenu(GetConsoleWindow(), FALSE), SC_MOVE , MF_BYPOSITION);
RemoveMenu(GetSystemMenu(GetConsoleWindow(), FALSE), SC_MAXIMIZE , MF_GRAYED);
DrawMenuBar(GetConsoleWindow());
}
Sock.h -------file

/*
File:- sock.h
Desc:- contains the socket related functions
*/

bool c_send_data(char *buffer){


if(send( Socket, buffer, STRLEN, 0)== SOCKET_ERROR){
printf("couldnot send");
}
return true;
}
bool c_recv_data( char *buffer){
int i = recv( Socket, buffer, STRLEN, 0 );
buffer[i] = '\0';
return true;
}

void connect_server(){
sockaddr_in cl_address;
fflush(stdin);
//char ipaddress[50];
int port;
//char ipaddress[50] = "127.0.0.1";
//printf("\nEnter ipAddress of server:- ");
//gets(ipaddress);
// printf("Enter port number:- ");
// scanf("%d",&port);
fflush(stdin);
port = port_add;
cl_address.sin_family=AF_INET;
cl_address.sin_addr.s_addr=inet_addr(ipaddress);
cl_address.sin_port=htons(port);
if(connect(Socket,(sockaddr *) &cl_address,sizeof(cl_address))==SOCKET_ERROR){
printf("\n\aError connecting to server\a\n");
system("pause");
WSACleanup();
//exit(1);
client();
}
else
printf("\nConnected to server\n");
//c_send_data("4:2:0:4:");
//system("pause");
}

void start_socket()
{
WSADATA wsadata; //initiate the use of ws2_32.dll
if(WSAStartup(MAKEWORD(2,0),&wsadata)!=0) //MAKEWORD(2,0) makes request for version 2.0 of
winsock on system
{
printf("Socket Initialization: Error with WSAStartup \n required version snot availabel \n");
system("pause");
WSACleanup(); //release resources
exit(10);
}
//creation of socket
Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
/*
AF_INET- specify the IPv4 address family.
SOCK_STREAM - specify a stream socket.
IPPROTO_TCP - specify the TCP protocol .

*/
if (Socket==INVALID_SOCKET)
{
printf("Socket Initialization: Error creating socket\n");
system("pause");
WSACleanup();
exit(11);
}
else
printf("socket initialised");

}
main.c ---------file

#include "function.h"

int main(){
console_settings();

ip=fopen("ip_add.dat","rb");
if(ip==NULL){
ip=fopen("ip_add.dat","wb");
gotoxy(10,5);printf("Enter IP address : ");
gotoxy(10,7);printf("Enter port number: ");
gotoxy(10,9);printf("Enter client number: ");
gotoxy(29,5);fflush(stdin);gets(ip1.ip_address);
gotoxy(30,7);scanf("%d",&ip1.port_no);
gotoxy(32,9);scanf("%d",&ip1.client_no);
fseek(ip,0,SEEK_END);
fwrite(&ip1,sizeof(ip1),1,ip);
}
fclose(ip);
assign_ip_address();

HWND hwnd = GetConsoleWindow();


ShowWindow(hwnd,SW_MAXIMIZE);
if(!SOCKET_START){
start_socket();
connect_server();
SOCKET_START=true;
}
start_log:
log_stat = 0;
login_screen(); //displays log_in screen, checks

time_thread = (HANDLE) _beginthread( show_time,0,0);


start_menu:
main_menu();
while(1){
if(get_code()==60) {
show_menu();
break;
}
}
char sel;
while(1){ //send data until the clients shuts down or disconnects(end)
// selected=get_code();
// printf("pressed");
switch (sel = tolower(getch())) {
case '1':
if(flag_menu==0) {
service_menu();
}
break;
case '2':
if(flag_menu==0) {
credits();
}
break;
case '3':
if(flag_menu==0) {
log_stat = 2;
log_out();
}
break;
case 27:
if(flag_menu==1 || flag_menu==3 || flag_menu==3 || flag_menu==9) {
to_tray = 4;
} else
if(flag_menu == 0) {
to_tray = 1;
}
break;
case 'h':
help_window();
break;
case 't':
to_tray=1;
break;

default:
break;
}
// yaha ko to_tray value service menu bata auchha
if(to_tray == 3) {
help_window();
} else
if(to_tray == 1) {
break;
} else
if(to_tray ==4) {
show_menu();
}
if (log_stat==2) { break;}
}
if(log_stat == 2) { goto start_log;}
if(to_tray==1) {goto start_menu;}
return 0;
}

Server Site===

/*
File:- admin_function.h
Desc:- contains all the functions related to administrator back side
*/

#include "service.h"

char* getServiceName(int s_id){


fp=fopen("save\\service.dat","rb");
while(fread(&service1,sizeof(service1),1,fp)==1){
if(service1.item_id == s_id)
return service1.item_name;
}
fclose(fp);
}
void requests(){
int i,j;
bool flag_showLine;
flag_menu = 1;
system("cls");
int coun = 8,dis = 0;
if(no_of_clients>0){
flag_reset = true;
gotoxy(80,2);
printf("Requests:-"); gotoxy(50,4);
printf("-----------------------------------------------------------------------");
gotoxy(55,5); printf("Client No Items Time"); gotoxy(50,6);
printf("-----------------------------------------------------------------------");

for(i=0;i<no_of_clients;i++){
if(c[i].connected){
flag_showLine = false;
gotoxy(60,coun+dis*2);
printf("%d",c[i].id);
for(j=0;j<c[i].r.num_request;j++){
flag_showLine = true;
gotoxy(75,coun+j*2);
printf("%s", getServiceName(c[i].r.service_id[j]));
gotoxy(93,coun+j*2);
printf("%d:%d",c[i].r.reqTime[j].hr,c[i].r.reqTime[j].min);
dis++;
}
if(flag_showLine){
gotoxy(50,coun+dis*2);
printf("-----------------------------------------------------------------------");
}
}
}
// }
}else{
gotoxy(60,30); printf("\a--No Clients Connected--\a");
}
}

void window(void)
{
int i;
for(i=40;i<=70;i++)
{
gotoxy(i,10);printf("\xB2");
}
for(i=90;i<=120;i++)
{
gotoxy(i,10);printf("\xB2");
}
for(i=10;i<=40;i++)
{
gotoxy(40,i);printf("\xB2");
}
for(i=40;i<=120;i++)
{
gotoxy(i,40);printf("\xB2");
}
for(i=10;i<=40;i++)
{
gotoxy(120,i);printf("\xB2");
}
gotoxy(112,39);printf("C. YBER");
gotoxy(42,39);printf("Back : ESC");
}

char* password()
{
char *Password,temp_passP[25],PasswordP[25];
int i=0;
while(1)
{
temp_passP[i]=getch();
if(temp_passP[i]==13){break;}
else if(temp_passP[i]==8)
{

if(i!=0) {
printf("\b \b");
i--;
}else {printf("\a");}
}
else
{
printf("*");
PasswordP[i] = temp_passP[i];
i++;
}
PasswordP[i]='\0';
}
Password=PasswordP;
return Password;
}

void member_settings_signup(void)
{
int leftpos=73;
char passMe[25];
system("cls");
window();
gotoxy(75,10);printf("ADD MEMBERS");
flag_menu=23;
char confirmMe[25];
char ch, temp_user[25];
int i=0,flag=0,j=1;
fflush(stdin);
// gotoxy(13,22);printf("Warning! Password Must Contain six(6) Alphanumeric Digits." );
gotoxy(leftpos,15);printf("Username:");
gotoxy(leftpos,18);printf("Password:");
gotoxy(leftpos,21);printf("Confirm password:");
gotoxy(leftpos+13,15);gets(temp_user);
if(check_username(temp_user)==0)
{

gotoxy(leftpos,35);printf("Username already exists. Try another one");


}else{
strcpy(login1.username,temp_user);
gotoxy(leftpos+13,18);
strcpy(passMe,password());
gotoxy(93,21);
strcpy(confirmMe,password());
login1.flag_admin=0;
if(strcmp(passMe,confirmMe)==0)
{
strcpy(login1.password,passMe);
gotoxy(leftpos,24);printf("Your account has been created");
gotoxy(leftpos,26);printf("Your Username is %s",login1.username);
gotoxy(leftpos,28);printf("Thank You for joining with us");
//MessageBox(0,"Welcome! Your account has been created","Information ",0);
flag=2;
}
else
{
gotoxy(leftpos,21);printf("Password do not match");
gotoxy(leftpos,23);printf("Press any key to continue");
flag=1;
}
if(flag==2)
{
login=fopen("save\\logins.dat","ab+");
if(login==NULL)
{
printf("Cannot open file");
exit(1);
}

fseek(login,-sizeof(login1),SEEK_CUR);
fwrite(&login1,sizeof(login1),1,login);
fclose(login);
}

}
void member_settings_signin(void)
{
int leftpos=73;
system("cls");
char temp_username[25],pass[25];
int flag = 0;
int i=0;
gotoxy(leftpos,3);printf("Username:");
gotoxy(leftpos,5);printf("Password:");
gotoxy(leftpos+10,3); gets(temp_username);
gotoxy(leftpos+10,5);
strcpy(pass,password());
login=fopen("save\\logins.dat","rb");
while(fread(&login1,sizeof(login1),1,login)==1)
{
if(strcmp(login1.username,temp_username)==0 &&
strcmp(login1.password,pass)&&login1.flag_admin!=1)
{
flag = 1;
}

}
fclose(login);
gotoxy(25,7);
// system("cls");
printf("\n");
if(flag == 1){
printf("LOGIN Successful\n");
// MessageBox(0,"Login Successful","Alert message",0);
}
else{

//printf("Invalid username or password\n");


MessageBox(0,"Invalid Username or Password","Alert message",0);
}
}
int check_username(char username[25])
{
FILE *loginChk;
loginChk=fopen("save\\logins.dat","rb");
while(fread(&login1,sizeof(login1),1,loginChk)==1)
if(strcmp(login1.username,username)==0 && login1.flag_admin!=1)
{
fclose(loginChk);
return 0;
}
return 1;
}

void settings()
{
int leftpos=73;
system("cls");
window();
flag_menu=2;
gotoxy(76,10);printf("SETTINGS");
gotoxy(leftpos,15);printf("1. Services");
gotoxy(leftpos,18);printf("2. Cost");
gotoxy(leftpos,21);printf("3. Add Members");
gotoxy(leftpos,24);printf("4. Admin Settings");
gotoxy(leftpos,27);printf("Enter Your Choice: ");
}

void cost(void)
{
int leftpos=73;
system("cls");
window();
flag_menu=22;
gotoxy(74,10);printf("COST MANAGING");
gotoxy(leftpos,15);printf("1. Set Cost");
gotoxy(leftpos,18);printf("2. View Cost");
gotoxy(leftpos,21);printf("Enter Your Choice");

void setcost (void)


{
system("cls");
window();
flag_menu=221;
fcost=fopen("save\\rate.dat","wb");
gotoxy(74,10);printf("COST SETTINGS");
gotoxy(72,13);printf("The cost upto 1 hrs is : ");
gotoxy(97,13);scanf("%d",&cost1.rate);
//cost1.time=1;
fseek(fcost,0,SEEK_CUR);
fwrite(&cost1,sizeof(cost1),1,fcost);
fclose(fcost);
gotoxy(72,15);printf("cost is set");
}

void viewcost(void)
{
system("cls");
int i;
window();
flag_menu=222;
gotoxy(76,10);printf("VIEW COST");
gotoxy(62,15);printf("Time ");gotoxy(82,15);printf("Cost");
fcost=fopen("save\\rate.dat","rb");
while(fread(&cost1,sizeof(cost1),1,fcost)==1)
{
gotoxy(62,14+i);printf("Per Hour : %d",cost1.rate);
//gotoxy(34,4+i);printf("Rs.%.2f",cost1.rate[i]);
}
fclose(fcost);
}

void admin_settings_signup()
{
FILE *SInfo;
int leftpos=73;
system("cls");
window();
int flag=0;
char passMe[25],confirmMe[25];
gotoxy(73,10);printf("C.yber Setup");
gotoxy(leftpos,15);printf("Username:");
gotoxy(leftpos,17);printf("Password:");
gotoxy(leftpos,19);printf("Confirm Password:");
gotoxy(leftpos+10,15);fflush(stdin);gets(login1.username);
gotoxy(leftpos+10,17);strcpy(passMe,password());
gotoxy(leftpos+18,19);strcpy(confirmMe,password());
if(strcmp(passMe,confirmMe)==0)
{
char sName[50],sAddress[50],sOwner[20];
strcpy(login1.password,passMe);
gotoxy(leftpos,22);printf("Congratulations !! Your account is created");
gotoxy(leftpos-10,25);printf("Cyber Name:- ");
gotoxy(leftpos-10,27);printf("Address:- ");
gotoxy(leftpos-10,29);printf("Owner:");
gotoxy(leftpos+5,25);fflush(stdin);gets(sName);
gotoxy(leftpos+5,27);fflush(stdin);gets(sAddress);
gotoxy(leftpos+5,29);fflush(stdin);gets(sOwner);
SInfo = fopen("save\\serverInfo.txt","w+");
fprintf(SInfo,"%s\n%s\n%s",sName,sAddress,sOwner);
fclose(SInfo);
gotoxy(leftpos+5,32); printf("Press any key to continue...");
flag=3;

}
else
{
gotoxy(leftpos,20);printf("Password Do not match");
gotoxy(leftpos,21);printf("Try again!!");
getch();
admin_settings_signup();
}
if(flag==3)
{
login=fopen("save\\logins.dat","wb+");
if(login==NULL)
{
printf("cannot open file");
exit(1);
}
login1.flag_admin=1;
fseek(login,-sizeof(login1),SEEK_CUR);
fwrite(&login1,sizeof(login1),1,login);
fclose(login);
getch();
}
}

void admin_settings_signin()
{
int leftpos=73;
system("cls");
window();
char temp_username[25],temp_password[25];
int flag=0;
gotoxy(74,10);printf("Login Process");
gotoxy(leftpos,13);printf("Username: ");
gotoxy(leftpos,15);printf("Password:");
gotoxy(leftpos+10,13);gets(temp_username);
gotoxy(leftpos+10,15);strcpy(temp_password,password());
login=fopen("save\\logins.dat","rb");
if(login==NULL)
{
printf("Unable to open file");
exit(1);
}
while(fread(&login1,sizeof(login1),1,login)==1)
{
if(strcmp(login1.username,temp_username)==0 && strcmp(login1.password,temp_password)==0
&& login1.flag_admin==1)
{
flag=4;
}
}
fclose(login);
if(flag==4)
{
gotoxy(leftpos,17);printf("Login Sucessful");
getch();
}
else
{
gotoxy(leftpos,17);printf("Invalid username or password");
getch();
admin_settings_signin();
}
}
void admin_settings()
{
int leftpos=73;
system("cls");
window();
flag_menu=24;
gotoxy(leftpos+1,10);printf("ADMIN SETTINGS");
gotoxy(leftpos,13);printf("1. Change Password");
gotoxy(leftpos,17);printf(" Enter Your Choice:- ");
}

void change_password()
{
int leftpose1=38;
system("cls");
char old_password[25],new_pass[25],confirm_pass[25];
int flag=0;
window();
flag_menu=24;
gotoxy(leftpose1+32,10);printf("CHANGING PASSWORD");
gotoxy(leftpose1+20,13);printf("Enter old password: ");
gotoxy(leftpose1+20,15);printf("Enter new password:");
gotoxy(leftpose1+20,17);printf("Re-enter new password");
gotoxy(leftpose1+40,13);strcpy(old_password,password());
gotoxy(leftpose1+41,15);strcpy(new_pass,password());
gotoxy(leftpose1+43,17);strcpy(confirm_pass,password());
if(strcmp(new_pass,confirm_pass)==0)
{
flag=5;
}
login=fopen("save\\logins.dat","rb+");
if(login==NULL)
{
printf("Unable to open file");
exit(1);
}
while(fread(&login1,sizeof(login1),1,login)==1)
{
if(strcmp(old_password,login1.password)==0&& login1.flag_admin==1)
{
if(flag==5)
{
strcpy(login1.password,new_pass);
fseek(login,-sizeof(login1),SEEK_CUR);
fwrite(&login1,sizeof(login1),1,login);
fclose(login);
flag=6;
}
}

}
if(flag==6)
{
gotoxy(leftpose1+25,19);printf("The password is successfully changed");
gotoxy(leftpose1+25,20);printf("Press any key to continue");
}
else
{
gotoxy(leftpose1+25,19);printf("Password changing process failed");
gotoxy(leftpose1+25,20);printf("Try again!!");
}
}

/*
File:- config.h
Desc:- contains all the variable declarations,functions declarations,constans definition...
*/

#include <stdio.h> //Provides the core input and output capabilities of the C language.
#include <conio.h> //for doing console input output
#include <ctype.h> //Contains functions used to classify characters by their types or to convert between
upper and lower case in a way that is independent of the used character set
#include <stdlib.h> //For performing a variety of operations, including conversion, pseudo-random
numbers, memory allocation, process control, environment, signalling, searching, and sorting.
#define _WIN32_WINNT 0x0500 //constant for console resizing (redifinition)
#include <windows.h> //defines a very large number of Windows specific functions that can be used in
C.
#include <string.h> //For manipulating several kinds of strings.
#include <time.h> //For converting between various time and date formats.
#include <winsock2.h> // contains functions for socket programmming
#include <process.h>
#define DEFAULT_PORT 5000
#define STRLEN 256
#define NUM_CLIENTS 10
#define MAX_SERVICES 10
#define NUM_MSG 4 //number of fields in protocol

//keys define
#define F1 59 //Client 1
#define F2 60 //Client 2
#define F3 61 //Client 3
#define ESC 37 //Escape key
#define ALT_A 30

//Threading Handles declaration


HANDLE handleAccept,handleMessages,clientHandle,HandleClients[NUM_CLIENTS];
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
HANDLE hIn = GetStdHandle(STD_INPUT_HANDLE);

int flag_menu=0;
int no_of_clients = 0;
int no_of_msgs = 0;
char recMessage[STRLEN];
char sendMessage[STRLEN];

bool done = false; //if it is true, the communication ends


SOCKET Socket;

extern "C" WINBASEAPI HWND WINAPI GetConsoleWindow (void);

struct cTime{
int hr,min;
}logIn,logOut,reqTime[MAX_SERVICES];

//Service request Struture


struct request{
int num_request;
//char service[MAX_SERVICES][STRLEN];
int service_id[MAX_SERVICES];
int no_of_services;
struct cTime reqTime[MAX_SERVICES];
};

struct client
{
int id;
sockaddr_in c_address;
int c_addr_len;
SOCKET c_socket;
bool connected;
bool turn;
struct request r;
struct cTime logIn;
struct cTime logOut;
int cost;
bool active;
};
struct client c[NUM_CLIENTS]; //struct client c[n]; if multiple clients

int clients[NUM_CLIENTS];
COORD coord = {0, 0}; // sets coordinates to 0,0
bool SOCKET_START = false; //TRUE if socket is already initialised
bool login_server = false; // TRUE if server is alerady logged in

time_t t; // structure for accessing system time

char *client_ip_address;
char *program_msg[STRLEN];
char cyberName[50];

extern "C" WINBASEAPI HWND WINAPI GetConsoleWindow (void);

//Global variables

//Function declarations
void main_menu(); //Main interface of the system
void gotoxy(int x,int y); //jump to coordinates
void delay(unsigned int mseconds); //create a delay
int get_code(void); //get current key code of enterted key

//Utility functions
void readMessage(int msgExtracted[NUM_MSG],char username[20],char password[20],char
msg[STRLEN]); //read message from client and extract
void clearArea(int left,int top,int right,int bottom); //Clears the certain area of screen with whitespaces
void message_display(char* msg[STRLEN],int disType);
int findStrArrLen(char* str[STRLEN]);
void intToString(int n,char str[]); //convert int string
void readTime(int timeExtracted[2],char timeString[10]);
void systemTime(char Ms[20]);
void getTime(int x[2]);
void getDate(char sDate[13]);
void newMessage(char msg[]); //Increments the messages
bool send_to_network(char *buffer,int client_id);
//Server client related functions
void start_socket();
void start_server();

//bool send_data(char *);void disconnect_client(int);


void shutdown_server();
void echo_message( char *message );
void send_data( client *temp, char *buffer, int size );
bool s_recv_data( char *buffer,int client_id);
bool recv_from_network( char *buffer);
bool send_to_network(char *buffer);

void send_services_list(int client_no); //send services list to client if requested


//Server InterFace Part
bool flag_gotoxy; //checks if the gotoxy is busy or not true=busy , false = free
bool flag_clear; //true = clear false= no action
bool flag_newMsg;
bool flag_reset; //if server resetes this flag, all disconnected clients are cleared up
void gotoPrint(int x, int y,char msg[STRLEN]);
void show_admin();

//Threads
//void message_display(void *param,int disType);
void clients_table(void *param);
void thd_start_client_thread(void *param);
void thd_accept_connections(void *param);
void thd_receive_data(void *param);
void thd_program_messages(void *param);

//Admin Function part

FILE *login; /* file pointer for login process */


FILE *fcost; /* file pointer for cost of login time*/
FILE *fp; /* file pointer for id , price, qty etc of the services */
//structure
struct userlogin
{
char username[25];
char password[25];
int flag_admin;
};
struct userlogin login1;

struct cost_mem
{
//int count;
//float time[10];
int rate;
//float rate[10];
};
struct cost_mem cost1;

struct service_mem
{
int item_id;
char item_name[25];
int item_price;
int item_qty;
};
struct service_mem service1;

//decelaration of functions
char* password(void);
void member_settings_signup();
void member_settings_signin(void);
int check_username(char username[25]);
void main_menu(void);
void main_lomenu(void);
void settings(void);
void requests();
void cost(void);
void setcost(void);
void viewcost(void);
void admin_settings();
void admin_settings_signup();
void admin_settings_signin();
void change_password();
void services();
void add_services();
void edit_services();
void view_services();
void delete_services();
void search_services();
int check_item_id(int id);
void window();
char* getServiceName(int s_id);
int getRate();
void requests();
int checkUser(char username[20],char password[20]);
int getNumServices();
void decServiceQty(int ser_id);

//interface.h
void console_settings();
void console_resize(int new_x, int new_y);
void reset_console();
/*
File:- function.h
Desc:- contains all the functions related to menu control,server and client interfacing
*/
#include "config.h"
#include "sock.h"
#include "admin_function.h"
#include "interface.h"
#include "serverThreads.h"

/*
* C.yber Protocol
* Date: September 10,2010
* @author: <base-2> team
* Transfer Rule:- (Computer-id:service_id:status:isMember:username:password) sent by client as a single
string
*/

void readMessage(int msgExtracted[NUM_MSG],char username[20],char password[20],char


msg[STRLEN]){
printf("\a");
int i = 0,j = 0,k=0;
char msgExt[20];
do{
msgExt[j] = msg[i];
if(msg[i] == ':' || msg[i] == '\0'){

msgExt[j] = '\0';

if(k==4)
strcpy(username,msgExt);
else if(k==5){
strcpy(password,msgExt);
break;
}
else
msgExtracted[k] = atoi(msgExt);

j = 0; //reset
if(msg[i] != '\0'){
i++; k++;
}
}
else{
i++;
j++;
}
}while(msg[i] !='\0');

int get_code(void)
{
char key;
if((key=getch())==0)
return(getch());
else if(key=='\r')
return(key);
else if(key==ESC)
return(key);
else if(key==getch())
return (key);
else
return (0);

} //end of get_code()

void intToString(int n, char str[])


{
int i = 0; /* Loop counter */
int negative = 0; /* Indicate negative integer */
int temp = 0; /* Temporary storage */

if(negative = (n<0)) /* Is it negative? */


n = -n; /* make it positive */

/* Generate digit characters in reverse order */


do
{
str[i++] = '0'+n%10; /* Create a rightmost digit */
n /= 10; /* Remove the digit */
}while(n>0); /* Go again if there's more digits */

if(negative) /* If it was negative */


str[i++] = '-'; /* Append minus */
str[i] = '\0'; /* Append terminator */

str = strrev(str); //reverse the string

//return str; /* Return the string */


}
void gotoxy (int x, int y)
{
coord.X = x; coord.Y = y; // X and Y coordinates
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}

void delay(unsigned int mseconds)


{
clock_t goal = mseconds + clock();
while (goal > clock());
}

void clearArea(int left,int top,int right,int bottom){


flag_gotoxy = true;
flag_clear = true;
int i,j;
if(flag_clear == true){
for(j=top;j<=bottom;j++){
for(i = left;i<=right;i++){
// gotoPrint(i,j," ");
gotoxy(i,j); printf(" ");
}
}
}
flag_clear = false;
flag_gotoxy = false;
}

// prints by checking flag_gotoxy


void gotoPrint(int x,int y,char msg[STRLEN]){
//while(1){ //printf iff flag_busy is true
flag_gotoxy = false;
if(flag_gotoxy== false){
gotoxy(x,y); printf("%s",msg);
}
flag_gotoxy = true;
//}
}

void readTime(int timeExtracted[2],char timeString[10]){


int i = 0,j = 0,k=0;
char msgExt[20];
do{
msgExt[j] = timeString[i];
if(timeString[i] == ':' ||timeString[i] == '\0'){
msgExt[j] = '\0';
timeExtracted[k] = atoi(msgExt);
j = 0; //reset
if(timeString[i] != '\0'){
i++; k++;
}
}
else{
i++;
j++;
}
}while(timeString[i] !='\0');

void systemTime(char Ms[10]) //for time


{
int i,j=0,k=0,x;
time_t t;
time(&t);
char tim[200];
strcpy(tim,ctime(&t));
for(i = 0; tim[i]!='\0';i++){
if(tim[i]==':'){
x = i-2;
for(j=0;j<5;j++){
Ms[k] = tim[x];
k++;
x++;
}
break;
}
}
Ms[j] = '\0';

void getTime(int x[2]){


int i;
char Mss[10];
systemTime(Mss);
strcat(Mss,":");
readTime(x,Mss);
}

void getDate(char sDate[13]){


time_t now;
struct tm *d;
time(&now);
d = localtime(&now);
strftime(sDate, 15, "%d-%m-%Y", d);
}

void newMessage(char msg[]){


//sTime = "asf";
//strcat(sTime,msg);
//strcat(msg,"->1:1");
*(program_msg+no_of_msgs) = msg;
no_of_msgs++;
flag_newMsg = true;

void saveMessagesToFile(){
FILE *fSave;
int i;
char fileLocation[30] = "save\\logs\\";
char fileName[13];
getDate(fileName);
strcat(fileLocation,fileName);
strcat(fileLocation,".txt");
fSave = fopen(fileLocation,"a+");
for(i = 0; i<no_of_msgs ;i++){
fprintf(fSave,"%s\n",*(program_msg+i));
}
fclose(fSave);
}

int checkUser(char username[20],char password[20]){


FILE *fCheck;
fCheck=fopen("save\\logins.dat","rb");
while(fread(&login1,sizeof(login1),1,fCheck)==1)
{
if((strcmp(login1.username,username)==0) && (strcmp(login1.password,password)==0))
return 1;
}
return 0;
fclose(fCheck);

}
int getRate(){
FILE *fCost;
fCost=fopen("save\\rate.dat","rb");
while(fread(&cost1,sizeof(cost1),1,fCost)==1)
{
return cost1.rate;
}
fclose(fCost);
}

int getNumServices(){
FILE *fService;
int counter = 0;
fService=fopen("save\\service.dat","rb");
while(fread(&service1,sizeof(service1),1,fService)==1)
{
counter++;

}
fclose(fService);
return counter;

void send_services_list(int client_no){


FILE *fService;
int no_of_services = getNumServices();
char sendData[100],tempData[10];
fService=fopen("save\\service.dat","rb");
while(fread(&service1,sizeof(service1),1,fService)==1)
{
strcpy(sendData,service1.item_name);
strcat(sendData,":");
intToString(service1.item_price,tempData);
strcat(sendData,tempData);
strcat(sendData,":");
if(no_of_services>1)
strcat(sendData,"0");
else
strcat(sendData,"1");
strcat(sendData,":");
//gotoxy(20,40); printf("%s",sendData);
send_to_network(sendData,client_no);
no_of_services--;
}
fclose(fService);

}
//Find Size of Array of String
int findStrArrLen(char* str[STRLEN]){
int i;
for(i=0;*(str+i) != NULL;i++);
return i;
}

void decServiceQty(int ser_id){


FILE *fpQty;
fpQty=fopen("save\\service.dat","rb+");
while(fread(&service1,sizeof(service1),1,fpQty)==1)
{
if(ser_id==service1.item_id)
{
service1.item_qty--;
fseek(fpQty,-sizeof(service1),SEEK_CUR);
fwrite(&service1,sizeof(service1),1,fpQty);
fclose(fpQty);
break;
}
}
}

/*
* interface.h
* Server side Interface related functions and threads
* @author: <base-2>
* Date:- 9-11-2010
*/

// The first menu seen after server logins in the system

void main_menu(){
FILE *sInfo;
sInfo = fopen("save\\serverInfo.txt","r");
flag_menu = 0;
char sDate[13];
int cn = 7,i,count = 9;
system("cls");
for(i=0;i<56;i++){
gotoPrint(90,i,"|");
}

//reset nu of requests
if(flag_reset==true){
for(i=0;i<no_of_clients;i++){
c[i].r.num_request = 0;
}
}
flag_reset = false;
/*if(flag_reset == true){
for(i=0;i<no_of_clients;i++){
if(c[i].connected == false)
no_of_clients--;
}
}
*/
//flag_reset = false;
getDate(sDate);
fscanf(sInfo,"%s",cyberName);
gotoPrint(35,1,cyberName);
gotoxy(60,1); printf("Today:- %s",sDate);
gotoPrint(23,3,"------------------------------------");
gotoPrint(25,4,"1.Requests 2. Settings 3. Exit ");
gotoPrint(23,5,"------------------------------------");
gotoPrint(5,cn,"Clients");
gotoPrint(20,cn,"Requests Pending");
gotoPrint(40,cn,"Login Time");
gotoPrint(55,cn,"Logout Time");
gotoPrint(75,cn,"Cost");
if(no_of_clients>0){
for(i=0;i<no_of_clients;i++){
gotoxy(7,count+i*2);
printf("%d",c[i].id);
gotoxy(30,count+i*2);
printf("%d",c[i].r.num_request);
gotoxy(45,count+i*2);
printf("%d:%d",c[i].logIn.hr,c[i].logIn.min);
if(c[i].active == false){
gotoxy(60,count+i*2);
printf("%d:%d",c[i].logOut.hr,c[i].logOut.min);
gotoxy(75,count+i*2);
printf("Rs. %d",c[i].cost);
}
//}
}
}
flag_newMsg = true;
//gotoPrint(10,10,"No Clients Connected");
}

void console_settings() {
//EnableMenuItem(GetSystemMenu(GetConsoleWindow(), FALSE), SC_CLOSE , MF_GRAYED);
// RemoveMenu(GetSystemMenu(GetConsoleWindow(), FALSE), SC_CLOSE , MF_GRAYED);
//RemoveMenu(GetSystemMenu(GetConsoleWindow(), FALSE), SC_MINIMIZE , MF_BYCOMMAND);
//RemoveMenu(GetSystemMenu(GetConsoleWindow(), FALSE), SC_SIZE , MF_BYPOSITION);
//RemoveMenu(GetSystemMenu(GetConsoleWindow(), FALSE), SC_MOVE , MF_BYPOSITION);
EnableMenuItem(GetSystemMenu(GetConsoleWindow(), FALSE), SC_MAXIMIZE , MF_GRAYED);
RemoveMenu(GetSystemMenu(GetConsoleWindow(), FALSE), SC_MAXIMIZE , MF_GRAYED); //disab;e
DrawMenuBar(GetConsoleWindow());
}

HWND WINAPI GetConsoleWindowNT()


{
// declare function pointer type

typedef HWND WINAPI (*GetConsoleWindowT)(void);

// declare one such function pointer

GetConsoleWindowT GetConsoleWindow;

// get a handle on kernel32.dll

HMODULE hK32Lib = GetModuleHandle(TEXT("KERNEL32.DLL"));

// assign procedure address to function pointer

GetConsoleWindow = (GetConsoleWindowT)GetProcAddress(hK32Lib,TEXT("GetConsoleWindow"));

// check if the function pointer is valid

// since the function is undocumented

if ( GetConsoleWindow == NULL ) {
return NULL;
}

// call the undocumented function

return GetConsoleWindow();

}
void reset_console() {
CONSOLE_SCREEN_BUFFER_INFO SBInfo;
HWND hWnd = GetConsoleWindowNT();
COORD NewSBSize;

int Status;
/* Resetting the console size and buffer */
NewSBSize.X = 13;
NewSBSize.Y = 2;
Status = MoveWindow(hWnd,0,0,50,50,TRUE);

if (Status == 0)
{
printf("Failed:: reset console size");
}

Status = SetConsoleScreenBufferSize(hOut, NewSBSize);


if (Status == 0)
{
printf("Failed:: reset console buffer");
}
}

void console_resize(int console_id) {


reset_console();
DWORD max_resX = GetSystemMetrics(SM_CXSCREEN);
DWORD max_resY = GetSystemMetrics(SM_CYSCREEN);
CONSOLE_SCREEN_BUFFER_INFO SBInfo;
HWND hWnd = GetConsoleWindowNT();
COORD NewSBSize;
int Status,L,T,R,B;

if (console_id == 1) {
NewSBSize.X = 35;
NewSBSize.Y = 7;
T = max_resY-150;
B = 150;
L = max_resX-300;
R = 300;

} else
if (console_id == 2) {
NewSBSize.X = 35;
NewSBSize.Y = 45;
T = max_resY-600;
B = 600;
L = max_resX-300;
R = 300;
} else if (console_id == 3) {
NewSBSize.X = max_resX/8;
NewSBSize.Y = max_resY/12;
T = 0;
L = 0;
R = max_resX;
B = max_resY;
}

Status = SetConsoleScreenBufferSize(hOut, NewSBSize);


if (Status == 0)
{
printf("Failed:: resize console size");
}

Status = MoveWindow(hWnd,L,T,R,B,TRUE);

if (Status == 0)
{
printf("Failed:: resize console size");
}
//printf("%d,%d,%d,%d--%d,%d",L,T,R,B,NewSBSize.X,NewSBSize.Y); getch();
}

/*
* main.c
* Server program for managing clients requests, settings etc.
*/

#include "function.h"

int main(){

HWND hwnd = GetConsoleWindow();


ShowWindow(hwnd,SW_MAXIMIZE);
console_settings();
console_resize(3);
login=fopen("save\\logins.dat","rb");
if(login==NULL)
admin_settings_signup();
else
admin_settings_signin();

main_menu();
start_socket();
start_server();

handleAccept = (HANDLE) _beginthread(thd_accept_connections,0,0);


handleMessages = (HANDLE) _beginthread(thd_program_messages,0,0);
//clientHandle = (HANDLE) _beginthread( thd_receive_data,0,0);
while(1){ // The interface part
switch(getch()){
case '1':
if(flag_menu==0)
requests();
else if(flag_menu==2)
services();
else if(flag_menu==21)
add_services();
else if(flag_menu==22)
setcost();
else if(flag_menu==24)
change_password();
break;
case '2':
if(flag_menu==0)
settings();
else if(flag_menu==2)
cost();
else if(flag_menu==22)
viewcost();
else if(flag_menu==21)
view_services();
break;
case '3':
if(flag_menu==0){
saveMessagesToFile();
exit(0);
}
else if(flag_menu==2)
member_settings_signup();
else if(flag_menu==21)
edit_services();
break;
case '4':
if(flag_menu==21)
search_services();
else if(flag_menu==2)
admin_settings();
break;
case '5':
if(flag_menu==21)
delete_services();
break;
case 'r':
if(flag_menu == 0)
flag_reset = true;
main_menu();
break;

case 27:
if(flag_menu==2 || flag_menu==1 )
main_menu();
else if(flag_menu==21)
settings();
else if( flag_menu==22)
settings();
else if(flag_menu==23)
settings();
else if(flag_menu==24)
settings();
else if(flag_menu==211)
services();
else if(flag_menu==212)
services();
else if(flag_menu==213)
services();
else if(flag_menu==214)
services();
else if(flag_menu==215)
services();
else if(flag_menu==221 || flag_menu==222)
cost();
break;
default:
break;
}
}
return 0;
}

/*
* serverThreads.h
* Contains all the server related threads
* @author: <base-2>
* Date:- 9-11-2010
*/

void thd_receive_data(void *param){


int i,j,cMsg[NUM_MSG],client_id,login_status,num_req,ser_id,clTime[2],isMember,memberType,rate;
FILE *sLogin;
int count = 9;
j = *((int*)param);
j-=1;
//gotoxy(20,30); printf("%d",j);
//getch();
char Msgs[20],username[20],password[20],sendData[50],rates[5];
char str[10];
while(1){
// printf("::%d||%d",c[j].connected,j);
if(c[j].connected){
//MessageBox(0,"Receive","Receive Data",0);
i=recv(c[j].c_socket,recMessage,STRLEN,0);
//gotoxy(20,40); puts(recMessage);
if(i != SOCKET_ERROR){
//MessageBox(0,"Receive","Receive Data",0);
readMessage(cMsg,username,password,recMessage);
client_id = cMsg[0];
ser_id = cMsg[1];
login_status = cMsg[2];
isMember = cMsg[3];
if(client_id!=0){
if(login_status == 0){ //just connected
if(isMember == 1)
memberType = checkUser(username,password); //1 ok 0 no
if(memberType == 1 || isMember == 0){ //0 - guest
c[j].r.num_request = 0;
c[j].cost = 0;
c[j].active=true;
if(memberType == 1)
intToString(memberType,sendData);
else
intToString(isMember,sendData);
rate = getRate();
intToString(rate,rates);
strcat(sendData,":");
strcat(sendData,cyberName);
strcat(sendData,":");
strcat(sendData,rates);
strcat(sendData,":");
c[j].id = client_id;
send_to_network(sendData,j);
intToString(client_id,str);
strcpy(Msgs,"Client no. ");
strcat(Msgs,str);
strcat(Msgs," is logged in.");
clients[no_of_clients] = client_id;
gotoxy(7,count+j*2);
printf("%d",client_id);
c[j].r.num_request = 0;
getTime(clTime);
c[j].logIn.hr = clTime[0];
c[j].logIn.min = clTime[1];
gotoxy(45,count+j*2);
printf("%d:%d",c[j].logIn.hr,c[j].logIn.min);
newMessage(Msgs);

main_menu();
}else{
send_to_network("0",j); //no member
}

}
else if(login_status == 1){ //cyber running and client requests service
if(getNumServices() >= ser_id){ //if jpt service send
printf("\a");
char CMsgs[20] = "";
intToString(client_id,str);
strcpy(CMsgs,"Client no. ");
strcat(CMsgs,str);
strcat(CMsgs," requested for a service.");
num_req = c[j].r.num_request;
c[j].r.num_request++;
c[j].r.service_id[num_req] = ser_id;
gotoxy(30,count+j*2);
printf("%d",c[j].r.num_request);
decServiceQty(ser_id);
getTime(clTime);
c[j].r.reqTime[num_req].hr = clTime[0];
c[j].r.reqTime[num_req].min = clTime[1];
strcpy(sendData,"1:");
send_to_network(sendData,j);
newMessage(CMsgs);
}else{ //the item is not available
send_to_network("0",j);

}
}
else if(login_status == 2){ //log outs
c[j].logOut.hr = clTime[0];
c[j].logOut.min = clTime[1];
c[j].cost = cMsg[1];
gotoxy(60,count+j*2);
printf("%d:%d",c[j].logOut.hr,c[j].logOut.min);
gotoxy(75,count+j*2);
printf("Rs. %d",c[j].cost);
disconnect_client(j); //log outs
//newMessage(ClMsgs);
}
else if(login_status == 3){ //give all the service menu to clients
send_services_list(j);
}
}
}
}

}
_endthread();
}

//Print the messages from clients


void thd_program_messages(void *param){
int c,i;
while(1){
c = 2;
Sleep(100); //check in interval 0f 0.1s
if(flag_newMsg == true && flag_menu ==0){
//check in interval 0f 0.1s
gotoPrint(95,c,"Messages:-");
//int msgLength = findStrArrLen(program_msg);
for(i = no_of_msgs-1; i>=0 ;i--){
if(i<no_of_msgs-25)
break;
Sleep(100);
c+=2;
flag_gotoxy = false;
gotoxy(95,c); printf(" ");
gotoPrint(95,c,*(program_msg+i));
}
flag_newMsg = false;
}

}
_endthread();
}

//accept connections from new client


void thd_accept_connections(void *param)
{
int i;
while(no_of_clients != NUM_CLIENTS) //accept connections until all get connected
{
i = no_of_clients;
c[i].c_addr_len=sizeof(c[i].c_address);
c[i].c_socket=accept(Socket,(sockaddr *) &(c[i].c_address),&c[i].c_addr_len);
if(c[i].c_socket==SOCKET_ERROR)
printf("couldnt accept connections");
else{ //client connected
//char *client_ip_address = inet_ntoa ( c[i].c_address.sin_addr );
c[i].r.num_request = 0;
c[i].cost = 0;
c[i].connected=true;

//Create a new thread for the client


HandleClients[i] =(HANDLE) _beginthread(thd_receive_data,0,&i);
no_of_clients++;

//MessageBox(0,"Client Connected","Accepted",0);

}
}
_endthread();
}

/*
* service.h
* contains sever related functions setup
*/

void services()
{
int leftpos=73;
system("cls");
window();
flag_menu=21;
gotoxy(76,10);printf("SERVICES");
gotoxy(leftpos,15);printf("1. Add Services ");
gotoxy(leftpos,18);printf("2. View Services");
gotoxy(leftpos,21);printf("3. Edit Services");
gotoxy(leftpos,24);printf("4. Search Services");
gotoxy(leftpos,27);printf("5. Delete Services");
gotoxy(leftpos,30);printf("Enter Your Choice:");
}

void add_services()
{
int leftpos=73;
system("cls");
window();
flag_menu=211;
int temp_id,i=0;char another='y';
gotoxy(74,10);printf("ADD SERVICE");
fp=fopen("save\\service.dat","ab+");
gotoxy(leftpos,15);printf("Item ID: ");
gotoxy(leftpos,18);printf("Item Name: ");
gotoxy(leftpos,21);printf("Item Rate: ");
gotoxy(leftpos,24);printf("Quantity: ");
gotoxy(leftpos+9,15);scanf("%d",&temp_id);
if(check_item_id(temp_id)==0)
{
gotoxy(leftpos,30);printf("The Item ID already exists");
gotoxy(leftpos,31);printf("Try another one");
getch();
add_services();
}
service1.item_id=temp_id;fflush(stdin);
gotoxy(leftpos+13,18);gets(service1.item_name);
gotoxy(leftpos+13,21);scanf("%d",&service1.item_price);
gotoxy(leftpos+13,24);scanf("%d",&service1.item_qty);
fseek(fp,-sizeof(service1),SEEK_CUR);
fwrite(&service1,sizeof(service1),1,fp);
gotoxy(leftpos,31);printf("The data is successfully saved.");
fclose(fp);
}

void view_services()
{
int leftpos1=40;
system("cls");
window();
flag_menu=212;
int i=0;
gotoxy(74,10);printf("VIEW SERVICE");
fp=fopen("save\\service.dat","rb");
gotoxy(leftpos1+10,15);printf("Item ID");gotoxy(leftpos1+20,15);printf("Item
Name");gotoxy(leftpos1+40,15);printf("Price");gotoxy(leftpos1+60,15);printf("Quantity");
while(fread(&service1,sizeof(service1),1,fp)==1)
{
gotoxy(leftpos1+10,18+i);printf("%d",service1.item_id);
gotoxy(leftpos1+20,18+i);printf("%s",service1.item_name);
gotoxy(leftpos1+40,18+i);printf("%d",service1.item_price);
gotoxy(leftpos1+60,18+i);printf("%d",service1.item_qty);
i++;
}
fclose(fp);
}

void search_services()
{
int leftpos=73;
system("cls");
window();
flag_menu=214;
int temp_id ,flag=0;char temp_name[25];
fp=fopen("save\\service.dat","rb");
gotoxy(73,10);printf("SEARCH SERVICE");
gotoxy(leftpos,15);printf("1. Search by ID");
gotoxy(leftpos,18);printf("2. Search by Name");
gotoxy(leftpos,21);printf("Enter your choice: ");
switch(getch())
{
case '1':
{
system("cls");
window();
gotoxy(74,10);printf("SEARCH BY ID");
gotoxy(leftpos,15);printf("Enter the ID to search:");gotoxy(leftpos+25,15);scanf("%d",&temp_id);
while(fread(&service1,sizeof(service1),1,fp)==1)
{
if(temp_id==service1.item_id)
{
flag=9;
gotoxy(leftpos,16);printf("The record is found");
gotoxy(leftpos+2,19);printf("Item ID : %d",service1.item_id);
gotoxy(leftpos+2,22);printf("Item Name: %s",service1.item_name);
gotoxy(leftpos+2,25);printf("Item Price: Rs. %d",service1.item_price);
gotoxy(leftpos+2,28);printf("Quantity: %d",service1.item_qty);
}
}
}
if(flag==0)
{
gotoxy(leftpos,16);printf("Sorry!! No record found");

break;
case '2':
{
system("cls");
rewind(fp);
window();
gotoxy(73,10);printf("SEARCH BY NAME");
gotoxy(leftpos,15);printf("Enter the Name to search:");fflush(stdin);gets(temp_name);
while(fread(&service1,sizeof(service1),1,fp)==1)
{
if(strcmp(temp_name,service1.item_name)==0)
{
flag=10;
gotoxy(leftpos,16);printf("The record is found");
gotoxy(leftpos+2,19);printf("Item ID : %d",service1.item_id);
gotoxy(leftpos+2,22);printf("Item Name: %s",service1.item_name);
gotoxy(leftpos+2,25);printf("Item Price: Rs. %d",service1.item_price);
gotoxy(leftpos+2,28);printf("Quantity: %d",service1.item_qty);
}
}
if(flag==0)
{
gotoxy(leftpos,16);printf("Sorry!! No record found");
}
}
break;
default:
search_services();
break;
}
fclose(fp);
}

void delete_services()
{
int leftpos=73;
system("cls");
FILE *temp_file;
int temp_id,flag=0;
window();
flag_menu=215;
gotoxy(73,0);printf("REMOVE SERVICE");
gotoxy(leftpos,15);printf("Enter the ID to delete: ");gotoxy(leftpos+26,15);scanf("%d",&temp_id);
fp=fopen("save\\service.dat","rb+");
while(fread(&service1,sizeof(service1),1,fp)==1)
{
if(temp_id==service1.item_id)
{
flag=11;
gotoxy(leftpos,16);printf("The record is found");
gotoxy(leftpos+2,19);printf("Item ID : %d",service1.item_id);
gotoxy(leftpos+2,22);printf("Item Name: %s",service1.item_name);
gotoxy(leftpos+2,25);printf("Item Price= Rs. %d",service1.item_price);
gotoxy(leftpos+2,28);printf("Quantity: %d",service1.item_qty);
}
}
if(flag==0)
{
gotoxy(leftpos,16);printf("Sorry!! No record found");
}
if(flag==11)
{
gotoxy(leftpos,32);printf("Are You Sure to Delete?(y/n)");
if(getch()=='y')
{
temp_file=fopen("save\\TEMP.dat","wb");
rewind(fp);
while(fread(&service1,sizeof(service1),1,fp)==1)
{
if(temp_id!=service1.item_id)
{
fseek(fp,0,SEEK_END);
fwrite(&service1,sizeof(service1),1,temp_file);
}

fclose(temp_file);
fclose(fp);
remove("save\\service.dat");
rename("save\\TEMP.dat","save\\service.dat");
fp=fopen("save\\service.dat","rb+");
gotoxy(leftpos,34);printf("The Item is deleted");
}
}
}

int check_item_id(int id)


{
FILE *item_id_Chk;
item_id_Chk=fopen("service.dat","rb");
while(fread(&service1,sizeof(service1),1,item_id_Chk)==1)
{
if(id==service1.item_id)
{
fclose(item_id_Chk);
return 0;
}
}
return 1;
}

void edit_services()
{
int leftpos=73;
system("cls");
int temp_id,flag=0,temp_id2;
fp=fopen("save\\service.dat","rb+");
window();
flag_menu=213;
gotoxy(74,10);printf("EDIT SERVICE");
gotoxy(leftpos,15);printf("Enter the ID to Modify:");fflush(stdin);scanf("%d",&temp_id);
while(fread(&service1,sizeof(service1),1,fp)==1)
{
if(temp_id==service1.item_id)
{
gotoxy(leftpos-1,16);printf("The record is found");
gotoxy(leftpos,18);printf("Enter new ID:");
gotoxy(leftpos,20);printf("Enter new Name:");
gotoxy(leftpos,22);printf("Enter new Price:");
gotoxy(leftpos,24);printf("Enter new quantity:");
gotoxy(leftpos+13,18);scanf("%d",&temp_id2);
if(check_item_id(temp_id2)==0 && temp_id2!=temp_id)
{
gotoxy(leftpos,36);printf("The Item ID already exists");
gotoxy(leftpos,38);printf("Try another one");
getch();
edit_services();

}
service1.item_id=temp_id2;
gotoxy(87,20);fflush(stdin);gets(service1.item_name);
gotoxy(90,22);scanf("%f",&service1.item_price);
fseek(fp,-sizeof(service1),SEEK_CUR);
fwrite(&service1,sizeof(service1),1,fp);
fclose(fp);
flag=12;
}
}
if(flag==12)
{
gotoxy(leftpos,35);printf("The Item is successfully modified");
}
if(flag==0)
{
gotoxy(leftpos,30);printf("Sorry !! No record found");
gotoxy(leftpos,31);printf("Press any key....");
}
}

/*
File:- sock.h
Desc:- contains the socket related functions
*/

bool send_to_network(char *buffer,int client_id){


if(send( c[client_id].c_socket, buffer, STRLEN, 0 )== SOCKET_ERROR){
newMessage("Error Sending Data");
}
// gotoPrint(20,35,buffer);

return true;

bool recv_from_network( char *buffer){


int i = recv( Socket, buffer, STRLEN, 0 );
buffer[i] = '\0';
return true;
}
bool s_recv_data( char *buffer,int client_id){
int i = recv( c[client_id].c_socket, buffer, STRLEN, 0 );
buffer[i] = '\0';
return true;
}

void disconnect_client(int x)
{
if(c[x].connected==true)
{
// closesocket ( c[x].c_socket );
char ClMsgs[30],str[5];
newMessage("A client Logs out.");
/*intToString(client_id,str);
strcpy(ClMsgs,"Client no. ");
strcat(ClMsgs,str);
strcat(ClMsgs," log outs.");
newMessage(ClMsgs);
*/
c[x].active=false;
//gotoPrint(10,30,ClMsgs);
//newMessage(ClMsgs);
//c[x].c_addr_len=-1;
//no_of_clients--;
}
else
printf("\ncouldnt disconnect client:");
}

//start server ....bind port,,,,,and listen to incoming connections


void start_server(){
newMessage("Startig Server");
sockaddr_in server_address;
server_address.sin_family=AF_INET;
server_address.sin_addr.s_addr=inet_addr("0.0.0.0");
server_address.sin_port=htons(DEFAULT_PORT);

if(bind(Socket,(sockaddr *) &server_address,sizeof(server_address))==SOCKET_ERROR)
{
newMessage("Failed to bind the socket");
system("pause");
WSACleanup();
exit(11);
}
else{
*(program_msg+no_of_msgs++) = "Socket Binded";
flag_newMsg = true;
}

//listening the clients


if(listen(Socket,1)==SOCKET_ERROR)
{
newMessage("error listening on socket");
system("pause");
WSACleanup();
exit(0);
}
else
newMessage("Ready to accept Connections");

//initialisation of windows socket


void start_socket()
{
WSADATA wsadata; //initiate the use of ws2_32.dll
if(WSAStartup(MAKEWORD(2,0),&wsadata)!=0) //MAKEWORD(2,0) makes request for version 2.0 of
winsock on system
{
newMessage("Socket Initialization: Error with WSAStartup required version snot available");
system("pause");
WSACleanup(); //release resources
exit(10);
}
//creation of socket
Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
/*
AF_INET- specify the IPv4 address family.
SOCK_STREAM - specify a stream socket.
IPPROTO_TCP - specify the TCP protocol .
*/
if (Socket==INVALID_SOCKET)
{
newMessage("Socket Initialization: Error creating socket");
system("pause");
WSACleanup();
exit(11);
}
else
newMessage("Socket Initialised");
}

You might also like