Tuesday 11 June 2013

Project- Supper Market Billing

Project- Supper Market Billing
#include<iostream>
#include<windows.h>
#include<conio.h>
#include<fstream>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<iomanip>
using namespace std;
//global variable declaration
int k=7,r=0,flag=0;
COORD coord = {0, 0};

void gotoxy(int x, int y)
{
 COORD coord;
 coord.X = x;
 coord.Y = y;
 SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
struct date
{int mm,dd,yy;};

ofstream fout;
ifstream fin;

class item
{
int itemno;
char name[25];
date d;
public:
void add()
{
cout<<"\n\n\tItem No: ";
cin>>itemno;
cout<<"\n\n\tName of the item: ";
cin>>name;
//gets(name);
cout<<"\n\n\tManufacturing Date(dd-mm-yy): ";
cin>>d.mm>>d.dd>>d.yy;
}
void show()
{
cout<<"\n\tItem No: ";
cout<<itemno;
cout<<"\n\n\tName of the item: ";
cout<<name;
cout<<"\n\n\tDate : ";
cout<<d.mm<<"-"<<d.dd<<"-"<<d.yy;
}
void report()
{
gotoxy(3,k);
cout<<itemno;
gotoxy(13,k);
puts(name);
}
int retno()
{
    return(itemno);

}

};

class amount: public item
{
float price,qty,tax,gross,dis,netamt;
public:
void add();
void show();
void report();
void calculate();
void pay();
float retnetamt()
{
    return(netamt);
}
}amt;

void amount::add()
{
item::add();
cout<<"\n\n\tPrice: ";
cin>>price;
cout<<"\n\n\tQuantity: ";
cin>>qty;
cout<<"\n\n\tTax percent: ";
cin>>tax;
cout<<"\n\n\tDiscount percent: ";
cin>>dis;
calculate();
fout.write((char *)&amt,sizeof(amt));
fout.close();
}
void amount::calculate()
{gross=price+(price*(tax/100));
netamt=qty*(gross-(gross*(dis/100)));
}
void amount::show()
{fin.open("itemstore.dat",ios::binary);
fin.read((char*)&amt,sizeof(amt));
item::show();
cout<<"\n\n\tNet amount: ";
cout<<netamt;
fin.close();
}

void amount::report()
{item::report();
gotoxy(23,k);
cout<<price;
gotoxy(33,k);
cout<<qty;
gotoxy(44,k);
cout<<tax;
gotoxy(52,k);
cout<<dis;
gotoxy(64,k);
cout<<netamt;
k=k+1;
if(k==50)
{gotoxy(25,50);
cout<<"PRESS ANY KEY TO CONTINUE...";
getch();
k=7;
system("cls");
gotoxy(30,3);
cout<<" ITEM DETAILS ";
gotoxy(3,5);
cout<<"NUMBER";
gotoxy(13,5);
cout<<"NAME";
gotoxy(23,5);
cout<<"PRICE";
gotoxy(33,5);
cout<<"QUANTITY";
gotoxy(44,5);
cout<<"TAX";
gotoxy(52,5);
cout<<"DEDUCTION";
gotoxy(64,5);
cout<<"NET AMOUNT";
}
}

void amount::pay()
{show();
cout<<"\n\n\n\t\t*********************************************";
cout<<"\n\t\t                 DETAILS                  ";
cout<<"\n\t\t*********************************************";
cout<<"\n\n\t\tPRICE                     :"<<price;
cout<<"\n\n\t\tQUANTITY                  :"<<qty;
cout<<"\n\t\tTAX PERCENTAGE              :"<<tax;
cout<<"\n\t\tDISCOUNT PERCENTAGE         :"<<dis;
cout<<"\n\n\n\t\tNET AMOUNT              :Rs."<<netamt;
cout<<"\n\t\t*********************************************";
}

int main()
{
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout<<setprecision(2);
fstream tmp("temp.dat",ios::binary|ios::out);
menu:
system("cls");
gotoxy(25,2);
cout<<"Super Market Billing ";
gotoxy(25,3);
cout<<"===========================\n\n";
cout<<"\n\t\t1.Bill Report\n\n";
cout<<"\t\t2.Add/Remove/Edit Item\n\n";
cout<<"\t\t3.Show Item Details\n\n";
cout<<"\t\t4.Exit\n\n";
cout<<"\t\tPlease Enter Required Option: ";
int ch,ff;
float gtotal;
cin>>ch;
switch(ch)
{case 1:ss:
system("cls");
gotoxy(25,2);
cout<<"Bill Details";
gotoxy(25,3);
cout<<"================\n\n";
cout<<"\n\t\t1.All Items\n\n";
cout<<"\t\t2.Back to Main menu\n\n";
cout<<"\t\tPlease Enter Required Option: ";
int cho;
cin>>cho;
if(cho==1)
{system("cls");
gotoxy(30,3);
cout<<" BILL DETAILS ";
gotoxy(3,5);
cout<<"ITEM NO";
gotoxy(13,5);
cout<<"NAME";
gotoxy(23,5);
cout<<"PRICE";
gotoxy(33,5);
cout<<"QUANTITY";
gotoxy(44,5);
cout<<"TAX %";
gotoxy(52,5);
cout<<"DISCOUNT %";
gotoxy(64,5);
cout<<"NET AMOUNT";
fin.open("itemstore.dat",ios::binary);
if(!fin)
{cout<<"\n\nFile Not Found...";
goto menu;}
fin.seekg(0);
gtotal=0;
while(!fin.eof())
{fin.read((char*)&amt,sizeof(amt));
if(!fin.eof())
{amt.report();
gtotal+=amt.retnetamt();
ff=0;}
if(ff!=0) gtotal=0;
}gotoxy(17,k);
cout<<"\n\n\n\t\t\tGrand Total="<<gtotal;
getch();
fin.close();
}
if(cho==2)
{goto menu;}
goto ss;
case 2:
db:
system("cls");
gotoxy(25,2);
cout<<"Bill Editor";
gotoxy(25,3);
cout<<"=================\n\n";
cout<<"\n\t\t1.Add Item Details\n\n";
cout<<"\t\t2.Edit Item Details\n\n";
cout<<"\t\t3.Delete Item Details\n\n";
cout<<"\t\t4.Back to Main Menu ";
int apc;
cin>>apc;
switch(apc)
{
case 1:fout.open("itemstore.dat",ios::binary|ios::app);
amt.add();
cout<<"\n\t\tItem Added Successfully!";
getch();
goto db;

case 2:
int ino;
flag=0;
cout<<"\n\n\tEnter Item Number to be Edited :";
cin>>ino;
fin.open("itemstore.dat",ios::binary);
fout.open("itemstore.dat",ios::binary|ios::app);
if(!fin)
{cout<<"\n\nFile Not Found...";
goto menu;
}
fin.seekg(0);
r=0;
while(!fin.eof())
{fin.read((char*)&amt,sizeof(amt));
if(!fin.eof())
{int x=amt.item::retno();
if(x==ino)
{flag=1;
fout.seekp(r*sizeof(amt));
system("cls");
cout<<"\n\t\tCurrent Details are\n";
amt.show();
cout<<"\n\n\t\tEnter New Details\n";
amt.add();
cout<<"\n\t\tItem Details editted";
}
}r++;
}
if(flag==0)
{cout<<"\n\t\tItem No does not exist...Please Retry!";
getch();
goto db;
}
fin.close();
getch();
goto db;

case 3:flag=0;
cout<<"\n\n\tEnter Item Number to be deleted :";
cin>>ino;
fin.open("itemstore.dat",ios::binary);
if(!fin)
{cout<<"\n\nFile Not Found...";
goto menu;
}
//fstream tmp("temp.dat",ios::binary|ios::out);
fin.seekg(0);
while(fin.read((char*)&amt, sizeof(amt)))
{int x=amt.item::retno();
if(x!=ino)
tmp.write((char*)&amt,sizeof(amt));
else
{flag=1;}
}
fin.close();
tmp.close();
fout.open("itemstore.dat",ios::trunc|ios::binary);
fout.seekp(0);
tmp.open("temp.dat",ios::binary|ios::in);
if(!tmp)
{cout<<"Error in File";
goto db;
}
while(tmp.read((char*)&amt,sizeof(amt)))
fout.write((char*)&amt,sizeof(amt));
tmp.close();
fout.close();
if(flag==1)
cout<<"\n\t\tItem Succesfully Deleted";
else if (flag==0)
cout<<"\n\t\tItem does not Exist! Please Retry";
getch();
goto db;
case 4:
goto menu;
default: cout<<"\n\n\t\tWrong Choice!!! Retry";
getch();
goto db;
}
case 3:system("cls");
flag=0;
int ino;
cout<<"\n\n\t\tEnter Item Number :";
cin>>ino;
fin.open("itemstore.dat",ios::binary);
if(!fin)
{cout<<"\n\nFile Not Found...\nProgram Terminated!";
goto menu;
}
fin.seekg(0);
while(fin.read((char*)&amt,sizeof(amt)))
{int x=amt.item::retno();
if(x==ino)
{amt.pay();
flag=1;
break;
}
}
if(flag==0)
cout<<"\n\t\tItem does not exist....Please Retry!";
getch();
fin.close();
goto menu;
case 4:system("cls");
gotoxy(20,20);
cout<<"ARE YOU SURE, YOU WANT TO EXIT (Y/N)?";
char yn;
cin>>yn;
if((yn=='Y')||(yn=='y'))
{gotoxy(12,20);
system("cls");
cout<<"************************** THANKS **************************************";
getch();
exit(0);
}
else if((yn=='N')||(yn=='n'))
goto menu;
else{goto menu;}
default:cout<<"\n\n\t\tWrong Choice....Please Retry!";
getch();
goto menu;
}
return 0;
}

PASCALS TRIANGLE

PASCALS TRIANGLE

#include<stdio.h>
#include<conio.h>
int main() {

        int a[15][15], i, j, rows, num = 25, k;
        printf("----------------------------------------------------------------------\n");
        printf("------------------made by BEST BLOG for TECHNOLOGY LOVERS -----------------\n");
        printf("----------------------------------------------------------------------\n");
        printf("\n\n\t\t C PROGRAM OF PASCALS TRIANGLE \n");
        printf("\n Enter the number of rows you want to show : ");
        scanf("%d", &rows);
        printf("\n\n\n");
        for (i = 0; i < rows; i++) {
               for (k = num - 2 * i; k >= 0; k--)
                     printf(" ");
               for (j = 0; j <= i; j++) {
                     if (j == 0 || i == j) {
                         a[i][j] = 1;
                     } else {
                         a[i][j] = a[i - 1][j - 1] + a[i - 1][j];
                     }
                     printf("%4d", a[i][j]);
               }
               printf("\n");
         }
         getch();
}

Saturday 8 June 2013

AMPLITUDE MODULATION


Depth First Search DFS

/*
 * File:   DFS.c
 * Author: SUVO
 * suvayan92@gmail.com
 * Created on 08 June, 2013, 03:34 PM
 */

#include <stdio.h>
#include <stdlib.h>
#define SIZE 100
#define debugMode 0 //for debugging purpose, set to 1 if want to start in debug mode

typedef enum{
    FALSE, TRUE
}boolean;

//////***********Implementation of Stack *****************///
//this stack can be used in DFS traversal of the graph.
typedef struct {
    char item[SIZE];
    int top;
}Stack;

void push(Stack *sp, char val){
    if (sp->top == SIZE-1){
        printf("\n:( Unable to process more than 100 elements\n Stack Overflow\nterminating process");
        return;
    }
    sp->item[++sp->top] = val;
}
char pop(Stack *sp){
    if (sp->top == -1){
        printf("Stack Underflow\n terminating the process\n");
        exit(0);
    }
    return sp->item[sp->top--];
}

/////****************END OF STACK IMPLEMENTATION***************************//
////*****************IMPLEMEMTATION OF QUEUE FOR BFS TRAVERSAL*****************/
typedef struct {
    char item[SIZE];
    int rear, front;
}Queue;

void queueInsert(Queue *qp, char val){
    if ((qp->rear+1)%SIZE==qp->rear){
        printf(":( Unusual situation, Queue overflow\nTerminating the process\n");
        exit(0);
    }
    qp->rear=(qp->rear+1)%SIZE;//moving the rear to the next location circularly.  
     //now place the value at the rear
    qp->item[qp->rear] = val;
}

char queueRetrieve(Queue *qp){
    if (qp->rear==qp->front){
        printf(":( Unusual situation\nQueue Underflow\nTerminating process\n");
        exit(0);
    }
    //move the front to the next location circularly
    qp->front = (qp->front+1)%SIZE;
    return qp->item[qp->front];
}

typedef struct GraphNode{
    char nodeVal;
    int STATUS;//used for BFS, DFS traversal
    //STATUS=0, node is un-touched, initial state.
    //STATUS=1, node is inserted into the STACK (BFS)/QUEUE (DFS)
    //STATUS=2, node has been processed;
    struct GraphNode *next;  
}GraphNode;

typedef struct AdjList{
     GraphNode *adjListHead;
     int nodeCount;
     int edgeCount;
}AdjList;

////**********************END OF QUEUE IMPEMENTATION ********************////


//function prototype declarations

void allocateAdjList(AdjList *);
void insertAtHead(GraphNode **, char);
void insertNeighbor(AdjList *, char , char);
void inputNodes(AdjList *);
void displayGraph(AdjList*);
char * getNeibors(AdjList*, char, int);
void initializeNodeStatus(AdjList *);
void DFS(AdjList *, char);
void BFS(AdjList *, char);


void initializeNodeStatus(AdjList *ptrAdjList){
    //initializes each nodes status field to 0
    int i;          
    for(i=0;i<ptrAdjList->nodeCount;i++){  
        (ptrAdjList->adjListHead+i)->STATUS=0;
       
    }
             
}


GraphNode* setNodeStatus(AdjList * ptrAdjList, char nodeChar, int STATUS){
    int i=0;
    for(i=0;i<ptrAdjList->nodeCount;i++){
        if((ptrAdjList->adjListHead+i)->nodeVal==nodeChar){
            (ptrAdjList->adjListHead+i)->STATUS=STATUS;
            break;
        }
    }
    return (ptrAdjList->adjListHead+i)->next;//return the neighbor list
}
int getNodeStatus(AdjList *ptrAdjList, char nodeChar){
    int i=0;
    for(i=0;i<ptrAdjList->nodeCount;i++){
        if((ptrAdjList->adjListHead+i)->nodeVal==nodeChar){          
            break;
        }
    }
    return (ptrAdjList->adjListHead+i)->STATUS;
}

void BFS(AdjList *ptrAdjList, char startNodeVal){
    int i, found;
    Queue queue;
    char pCh;
    GraphNode *neighborList;
    //initialize the stack;
    queue.rear = SIZE-1;
    queue.front = SIZE-1;
    //initialize graph
    initializeNodeStatus(ptrAdjList);
    //check if start node exists
    found = FALSE;
    for(i=0;i<ptrAdjList->nodeCount;i++){
        if ((ptrAdjList->adjListHead+i)->nodeVal==startNodeVal){
           found = TRUE;
           break;
        }
    }
    if (!found){
        printf(" :( Start Node: %c not found\n", startNodeVal);
        return;
    }
    //if start node found push it into the stack
    queueInsert(&queue, (ptrAdjList->adjListHead+i)->nodeVal);
    //set the status of the start node to 1;
    (ptrAdjList->adjListHead+i)->STATUS=1;
    printf("BFS LIST: ");
    while(queue.rear!=queue.front){
        pCh = queueRetrieve(&queue);
        printf("%4c",pCh);
        neighborList = setNodeStatus(ptrAdjList,pCh,2);
        for(;neighborList!='\0';neighborList=neighborList->next){
            if (getNodeStatus(ptrAdjList,neighborList->nodeVal)==0){
                queueInsert(&queue, neighborList->nodeVal);
                setNodeStatus(ptrAdjList,neighborList->nodeVal,1);
            }
        }
    }
 
    printf("\n");
 
 
}


void DFS(AdjList *ptrAdjList, char startNodeVal){
    int i, found;
    Stack stack;
    char pCh;
    GraphNode *neighborList;
    //initialize the stack;
    stack.top = -1;
    //initialize graph
    initializeNodeStatus(ptrAdjList);
    //check if start node exists
    found = FALSE;
    for(i=0;i<ptrAdjList->nodeCount;i++){
        if ((ptrAdjList->adjListHead+i)->nodeVal==startNodeVal){
           found = TRUE;
           break;
        }
    }
    if (!found){
        printf(" :( Start Node: %c not found\n", startNodeVal);
        return;
    }
    //if start node found push it into the stack
    push(&stack, (ptrAdjList->adjListHead+i)->nodeVal);
    //set the status of the start node to 1;
    (ptrAdjList->adjListHead+i)->STATUS=1;
    printf("DFS LIST: ");
    while(stack.top!=-1){
        pCh = pop(&stack);
        printf("%4c",pCh);
        neighborList = setNodeStatus(ptrAdjList,pCh,2);
        for(;neighborList!='\0';neighborList=neighborList->next){
            if (getNodeStatus(ptrAdjList,neighborList->nodeVal)==0){
                push(&stack, neighborList->nodeVal);
                setNodeStatus(ptrAdjList,neighborList->nodeVal,1);
            }
        }
    }
 
    printf("\n");
 
 
}

void allocateAdjList(AdjList *ptrAdjList){
    //allocate the array of head pointers for holding
    //the list of neighbor for each node.
    //if the function returns 0 then memory allocation failed
    //otherwise on success it returns the size of memory allocated (a +ve value)
    int i=0;
    ptrAdjList->adjListHead = (GraphNode *)malloc(sizeof(GraphNode) * ptrAdjList->nodeCount);
    if (ptrAdjList->adjListHead=='\0'){
        printf(":( Unable to allocate memory\nterminating the programe\n");
        exit(0);
    }
    //initialize head of each list
    for(i=0;i<ptrAdjList->nodeCount;i++){      
        ptrAdjList->adjListHead[i].next = '\0';
    }      
}

void insertAtHead(GraphNode **hp, char nodeValue){
    //inserts a node at the head of the linked list
    //hp is the pointer to the head (actually its the next pointer of the AdjList node array.)
    GraphNode *p;
    //create a new node.
    p = (GraphNode*)malloc(sizeof(GraphNode));  
    if (p == '\0'){
        printf("Unable to allocate memory for node\nterminating application\n");
        exit(0);
    }
    p->nodeVal = nodeValue;
    p->next = *hp;
    *hp = p;
}


void insertNeighbor(AdjList *ptrAdjList, char targetNode, char neighborNode){  
    //inserts the neighborNode as the neighbor of the targetNode;
    int i=0;

 
   if (debugMode)
     printf("@Debug %c-%c\n",targetNode,neighborNode);
 
 
   for(i=0;i<ptrAdjList->nodeCount;i++){
       if ((ptrAdjList->adjListHead+i)->nodeVal==targetNode){
           insertAtHead( &((ptrAdjList->adjListHead[i]).next),neighborNode);
       
       }
       else if ((ptrAdjList->adjListHead+i)->nodeVal==neighborNode){
           insertAtHead( &((ptrAdjList->adjListHead[i]).next),targetNode);        
       }
   }
}

void inputNodes(AdjList *ptrAdjList){
    int i=0;
    if (ptrAdjList->nodeCount==0)
        return;
    for(i=0;i<ptrAdjList->nodeCount;i++){
        printf("Next Node [characters allowed only(a,b,c,1,2,3 ....)]: ");
        scanf(" %c",&((ptrAdjList->adjListHead+i)->nodeVal));
    }
}

void inputEdges(AdjList *ptrAdjList){
    int i=0, ec,nc;
    char firstNode, secondNode;
    if (ptrAdjList->nodeCount==0)
        return;
    nc = ptrAdjList->nodeCount;
 
    do{
        printf("How Many edges: ");
        scanf(" %d",&ec);
        if (ec>((nc*(nc-1))/2))
        printf(" Invalid Number of edges...\ntry input again \n");
    }while(ec>(nc*(nc-1))/2);
 
    ptrAdjList->edgeCount=ec;
 
    for(i=0;i<ptrAdjList->edgeCount;i++){
        printf("Enter edge in the format a-b (if a,b forms an edge): ");      
        scanf(" %c%*c%c",&firstNode,&secondNode); //skipping the minus sign
     
     
        //insert the neighbour into the adjList
        insertNeighbor(ptrAdjList,firstNode, secondNode);
    }
 
}

void displayGraph(AdjList *ptrAdjList){
    int i,k=0,t;
    char nodeVal;
    GraphNode *p;
    boolean alreadyDisplayed;
    char displayed[ptrAdjList->edgeCount][ptrAdjList->edgeCount];
 
    printf("\n\tV={");
    for(i=0;i<ptrAdjList->nodeCount;i++){
        printf("%4c,",(ptrAdjList->adjListHead+i)->nodeVal);
    }
    printf("\b }\n\tE={");
    for(i=0;i<ptrAdjList->nodeCount;i++){
        nodeVal = (ptrAdjList->adjListHead+i)->nodeVal;
        if(debugMode){
            printf("@Debug: %c\n",nodeVal);
        }
        for(p=(ptrAdjList->adjListHead+i)->next;p!='\0';p=p->next){
            alreadyDisplayed= FALSE;
            for(t=0;t<k;t++){
                if ((displayed[t][0]==nodeVal && displayed[t][1]==p->nodeVal)||
                        (displayed[t][0]==p->nodeVal && displayed[t][1]==nodeVal)){
                    alreadyDisplayed=TRUE;
                    break;
                }
            }
            if(!alreadyDisplayed){
                printf("%c-%c,",nodeVal,p->nodeVal);
                displayed[k][0] = nodeVal;
                displayed[k++][1] = p->nodeVal;
            }
        }
     
    }
    printf("\b }\n\n");
}

int main(int argc, char** argv) {
    AdjList adjList;
    int choice;char startNode;
    printf("Enter total Number of Nodes: ");
    scanf(" %d",&adjList.nodeCount);
 
 
    allocateAdjList(&adjList);
    inputNodes(&adjList);
    inputEdges(&adjList);
 
    do{
        printf("1. BFS\n");
        printf("2. DFS\n");
        printf("3. Display\n");
        printf("4. Both DFS & BFS\n");
        printf("5. Exit\n");
        printf("Please enter your choice: ");
        scanf(" %d", &choice);
        switch(choice){
            case 1:printf("Enter Start Node: ");
                   scanf(" %c",&startNode);
                   BFS(&adjList,startNode);
                   break;
            case 2:printf("Enter Start Node: ");
                   scanf(" %c",&startNode);
                   DFS(&adjList,startNode);
                   break;
         
            case 3:displayGraph(&adjList);
                        break;
            case 4:printf("Enter Start Node: ");
                   scanf(" %c",&startNode);
                   DFS(&adjList,startNode);
                   BFS(&adjList,startNode);
                   break;
            case 5:exit(0);
            default: printf("Invalid Choice\n");                                
        }
     
 
    }while(1);
 
    return (EXIT_SUCCESS);
}

Sunday 2 June 2013

c,c++,computer architecture,tech news, gadget

To see the all post of this blog just click this below link.


http://suvotechmania.blogspot.in/search?updated-min=2013-01-01T00:00:00-08:00&updated-max=2014-01-01T00:00:00-08:00&max-results=24http://suvotechmania.blogspot.in/search?updated-min=2013-01-01T00:00:00-08:00&updated-max=2014-01-01T00:00:00-08:00&max-results=24

Want to trace/track any mobile?

Want to trace/track any mobile...........????????

locate /trace/track any mobile no, By visiting this site
http://suvotechmania.blogspot.in/ you will be able to know the exact location of that mobile no.
just see the right side of the upper phase of this blog and enter the 10 digits of the mobile
no., which you want to find and press the Trace button and you will be able to trace/track any mobile in India .

SWAPPING....----><-------

Swapping----><-----

#include<stdio.h>
#include<conio.h> 
int swap(int*, int*);
int main()
{
   int x, y;
   printf("Enter the value of x and y\n");
   scanf("%d%d",&x,&y);
   printf("Before Swapping\nx = %d\ny = %d\n", x, y);
   swap(&x, &y); 
   printf("After Swapping\nx = %d\ny = %d\n", x, y);
   getch();
   return 0;
   
}
int swap(int *a, int *b)
{
   int temp;
   temp = *b;
   *b = *a;
   *a = temp;   
}

Structure & pointer


Structure & pointer


#include <stdio.h>
#include <conio.h>


struct record
{
char name[20];
int roll;
};
struct record r,*p;

void main()
{
p=&r;
printf("\nEnter the name\n");
scanf("\n%s",&p->name);
printf("\nEnter the roll no\n");
scanf("%d",&p->roll);
printf("\n%s",p->name);
printf("\n%d",p->roll);
getch();
}

Tuesday 28 May 2013

Chinese hackers breach key US weapons designs

Chinese hackers have compromised the designs of some of America’s most sensitive and advanced weapons systems—including vital parts of the nation’s missile defenses, fighter aircraft and warships—the Washington Post reported Tuesday.
The Post cited a report prepared for the Pentagon by the Defense Science Board, which groups government officials and private sector experts. The document, “Re
silient Military Systems and the Advanced Cyber Threat,” paints a grim picture of cyber-espionage emanating from China only 10 days beforePresident Barack Obama meets in California with Chinese President Xi Jinping for the first time.
“I’m sure it will be a topic of discussion,” White House press secretary Jay Carney told reporters.
Beijing, riding a wave of robust economic growth, has been building up its military—and while the report does not accuse China's government of stealing the designs, such intrusions could help the world's most populous country enhance its armed forces.
The Post published the list of compromised systems here. It includes drone video systems, “directed energy” (a category that includes lasers and the like) and advanced Patriot missile systems. Also compromised were designs for the F/A 18 fighter jet, V-22 Osprey, F-35 Joint Strike Fighter, UH-60 Black Hawk helicopters and the Navy’s new Littoral Combat Ship meant to prowl the coasts. The list also includes the Terminal High Altitude Area Defense (THAAD) designed to shoot down ballistic missiles.
The report coincided with an Australian news report that Chinese hackers illegally accessed the designs for the new top secret headquarters of Australia's intelligence service, including communications cable layouts, server locations and security systems.
American officials have complained publicly and privately about Chinese cyber-espionage. Obama vowed in his State of the Union Address to take steps to protect the U.S. government and American businesses from such attacks—though he did not specifically name China, or Chinese hackers, as the main culprits.
But National Security Adviser Tom Donilon took aim at China in a blunt speech in March to the Asia Society in New York.
"From the president on down, this has become a key point of concern and discussion with China at all levels of our governments—and it will continue to be," Donilon warned.
"The United States will do all it must to protect our national networks, critical infrastructure, and our valuable public and private sector property. But, specifically with respect to the issue of cyber-enabled theft, we seek three things from the Chinese side," Donilon said. "First, we need a recognition of the urgency and scope of this problem and the risk it poses—to international trade, to the reputation of Chinese industry and to our overall relations. Second, Beijing should take serious steps to investigate and put a stop to these activities. Finally, we need China to engage with us in a constructive direct dialogue to establish acceptable norms of behavior in cyberspace."
The White House declined to comment specifically on the report. But a spokeswoman for the National Security Council, Laura Lucas, noted that in general "cybersecurity is one of this administration's top priorities, and we have long said that we are concerned about cyber intrusions emanating from China."
"What we have been seeking from China is for it to investigate our concerns and to start a dialogue with us on cyber issues," Lucas said, adding that the United States is "pleased" that China agreed last month to start a new working group to discuss the issue.
"Through such dialogue we seek longer-term changes in China's behavior, including by working together to establish norms against the theft of trade secrets and confidential business information," Lucas said. "This dialogue will take place within the context of our broader effort to build a cooperative partnership with China that solves shared global challenges."

Chinese hackers breach key US weapons designs

Chinese hackers have compromised the designs of some of America’s most sensitive and advanced weapons systems—including vital parts of the nation’s missile defenses, fighter aircraft and warships—the Washington Post reported Tuesday.

Thursday 23 May 2013

File Handling in C

File Handling in C


We frequently use files for storing information which can be processed by our programs. In order to store information permanently and retrieve it  we need to use files.

Files are not only used for data. Our programs are also stored in files.

The editor which you use to enter your program and save it, simply manipulates files for you.

The Unix commands cat, cp, cmp are all programs which process your files.

In order to use files we have to learn about File I/O i.e. how to write information to a file and how to read information from a file.

We will see that file I/O is almost identical to the terminal I/O that we have being using so far.

The primary difference between manipulating files and doing terminal I/O is that we must specify in our programs which files we wish to use.

As you know, you can have many files on your disk. If you wish to use a file in your programs, then you must specify which file or files you wish to use.

Specifying the file you wish to use is referred to as opening the file.

When you open a file you must also specify what you wish to do with it i.e. Read from the file, Write to the file, or both.

Because you may use a number of different files in your program, you must specify when reading or writing which file you wish to use. This is accomplished by using a variable called a file pointer.

Every file you open has its own file pointer variable. When you wish to write to a file you specify the file by using its file pointer variable.

You declare these file pointer variables as follows:


FILE  *fopen(), *fp1, *fp2, *fp3;


The variables fp1, fp2, fp3 are file pointers. You may use any name you wish.

The file <stdio.h> contains declarations for the Standard I/O library and should always be included at the very beginning of C programs using files.


Constants such as FILE, EOF and NULL are defined in <stdio.h>.

You should note that a file pointer is simply a variable like an integer or character.

It does not point to a file or the data in a file. It is simply used to indicate which file your I/O operation refers to.

A file number is used in the Basic language and a unit number is used in Fortran for the same purpose.

The function fopen is one of the Standard Library functions and returns a file pointer which you use  to refer to the file you have opened e.g.

    fp = fopen( “prog.c”,  “r”) ;

The above statement opens a file called prog.c for reading and associates the file pointer fp with the file.

When we wish to access this file for I/O, we use the file pointer variable fp to refer to it.

You can have up to about 20 files open in your program - you need one file pointer for each file you intend to use.



File I/O

The Standard I/O Library provides similar routines for file I/O to those used  for standard I/O.

The routine getc(fp) is similar to getchar()
and putc(c,fp) is similar to putchar(c).

Thus the statement

    c = getc(fp);

reads the next character from the file referenced by fp and the statement

    putc(c,fp);

writes the character c into file referenced by fp.



/* file.c: Display contents of a file on screen */

#include <stdio.h>

void main()
{
    FILE *fopen(), *fp;
    int c ;

    fp = fopen( “prog.c”, “r” );
    c = getc( fp ) ;       
    while (  c != EOF )
    {
        putchar( c );      
        c = getc ( fp );     
    }

    fclose( fp );
}

In this program, we open the file prog.c for reading.

We then read a character from the file. This file must exist for this program to work.

If the file is empty, we are at the end, so getc returns EOF a special value to indicate that the end of file has been reached. (Normally -1 is used for EOF)

The while loop simply keeps reading characters from the file and displaying them, until the end of the file is reached.

The function fclose is used to close the file i.e. indicate that we are finished processing this file.

We could reuse the file pointer fp by opening another file.

This program is in effect a special purpose cat command. It displays file contents on the screen, but only for a file called prog.c.

By allowing the user enter a file name, which would be stored in a string, we can modify the above to make it an interactive cat command:



/* cat2.c: Prompt user for filename and display file on screen */

#include <stdio.h>

void main()
{
    FILE *fopen(), *fp;
    int c ;
    char filename[40] ;

    printf(“Enter file to be displayed: “);
    gets( filename ) ;

    fp = fopen( filename, “r”); 

    c = getc( fp ) ;         

    while (  c != EOF )
    {
        putchar(c);        
        c = getc ( fp );   
    }

    fclose( fp );
}


In this program, we pass the name of the file to be opened which is stored in the array called filename, to the fopen function. In general, anywhere a string constant such as “prog,c” can be used so can a character array such as filename. (Note the reverse is not true).

The above programs suffer a major limitation. They do not check whether the files to be used exist or not.

If you attempt to read from an non-existent file, your program will crash!!

The fopen function was designed to cope with this eventuality. It checks if the file can be opened appropriately. If the file cannot be opened, it returns a NULL pointer. Thus by checking the file pointer returned by fopen, you can determine if the file was opened correctly and take appropriate action e.g.

          fp = fopen (filename, “r”) ;

     if ( fp  ==  NULL)
     {
           printf(“Cannot open %s for reading \n”, filename );
           exit(1) ; /*Terminate program: Commit suicide !!*/
     }

The above code fragment show how a program might check if a file could be opened appropriately.

The function exit() is a special function which terminates your program immediately.

exit(0) mean that you wish to indicate that your program terminated successfully whereas a nonzero value means that your program is terminating due to an error condition.

Alternatively, you could prompt the user to enter the filename again, and try to open it again:

          fp = fopen (fname, “r”) ;

     while ( fp  ==  NULL)
     {
           printf(“Cannot open %s for reading \n”, fname );

           printf(“\n\nEnter filename :” );
           gets( fname );

           fp = fopen (fname, “r”) ;
     }

In this code fragment, we keep reading filenames from the user until a valid existing filename is entered.

Exercise:     Modify the above code fragment to allow the user 3 chances to enter a valid filename. If a valid file name is not entered after 3 chances, terminate the program.

RULE: Always check when opening files, that fopen succeeds in opening the files appropriately.

Obeying this simple rule will save you much heartache.

Example 1: Write a program to count the number of lines and characters in a file.

Note: Each line of input from a file or keyboard will be terminated by the newline character ‘\n’. Thus by counting newlines we know how many lines there are in our input.




/*count.c : Count characters in a file*/
#include <stdio.h>

void main()
     /* Prompt user for file and count number of characters
        and lines in it*/
{
     FILE *fopen(), *fp;
     int c , nc, nlines;
     char filename[40] ;

     nlines = 0 ;
     nc = 0;

     printf(“Enter file name: “);
     gets( filename );

     fp = fopen( filename, “r” );    

     if ( fp == NULL )
     {
           printf(“Cannot open %s for reading \n”, filename );
           exit(1);      /* terminate program */
     }

     c = getc( fp ) ;            
     while (  c != EOF )
     {
           if ( c  ==  ‘\n’  )   
                nlines++ ;

           nc++ ; 
           c = getc ( fp );
     }

     fclose( fp );

     if ( nc != 0 )
     {
           printf(“There are %d characters in %s \n”, nc, filename );
           printf(“There are %d lines \n”, nlines );
     }
     else
           printf(“File: %s is empty \n”, filename );
}



Example 2: Write a program to display  file contents 20 lines at a time. The program pauses after displaying 20 lines until the user presses either Q to quit or Return to display the next 20 lines. (The Unix operating system has a command called more to do this ) As in previous programs, we read the filename from user and open it appropriately. We then process the file:

    read character from file

    while not end of file and not finished do
    begin

        display character

        if character is newline then
            linecount = linecount + 1;

        if linecount == 20 then
        begin
            linecount = 1 ;
            Prompt user and get reply;
        end

        read next character from file
    end




/* display.c: File display program */
/* Prompt user for file and display it 20 lines at a time*/

#include <stdio.h>

void main()
{
     FILE *fopen(), *fp;
     int c ,  linecount;
     char filename[40], reply[40];

     printf(“Enter file name: “);
     gets( filename );

     fp = fopen( filename, “r” );       /* open for reading */

     if ( fp == NULL )       /* check does file exist etc */
     {
           printf(“Cannot open %s for reading \n”, filename );
           exit();      /* terminate program */
     }

     linecount = 1 ;

     reply[0] = ‘\0’ ;
     c = getc( fp ) ;           /* Read 1st character if any */
     while ( c != EOF &&  reply[0] != ‘Q’ && reply[0] != ‘q’)
     {
           putchar( c ) ;       /* Display character */
           if ( c  ==  ‘\n’  )                 
                linecount = linecount+ 1 ;

           if ( linecount == 20 )
           {
                linecount = 1 ;
                printf(“[Press Return to continue, Q to quit]”);
                gets( reply ) ;
           }
           c = getc ( fp );
     }
     fclose( fp );
}

The string reply will contain the users response. The first character of this will be reply[0]. We check if this is ‘q’ or ‘Q’. The brackets [] in printf are used to distinguish the programs message from the file contents.


Example 3: Write a program to compare two files specified by the user, displaying a message indicating whether the files are identical or different. This is the basis of a compare command provided by most operating systems. Here our file processing loop is as follows:

read character ca from file A;
read character cb from file B;

while ca == cb and not EOF file A and not EOF file B
begin
    read character ca from file A;
    read character cb from file B;
end

if ca == cb then
        printout(“Files identical”);
else
        printout(“Files differ”);

This program illustrates the use of I/O with two files. In general you can manipulate up to 20 files, but for most purposes not more than 4 files would be used. All of these examples illustrate the usefulness of processing files character by character. As you can see a number of Operating System programs such as compare, type, more, copy can be easily written using character I/O. These programs are normally called system programs as they come with the operating system. The important point to note is that these programs are in no way special. They are no different in nature than any of the programs we have constructed so far.




/* compare.c : compare two files */

#include <stdio.h>
void main() 
{
     FILE *fp1, *fp2, *fopen();
     int ca, cb;
     char fname1[40], fname2[40] ;

     printf(“Enter first filename:”) ;
     gets(fname1);
     printf(“Enter second filename:”);
     gets(fname2);
     fp1 = fopen( fname1,  “r” );       /* open for reading */
     fp2 = fopen( fname2,  “r” ) ;      /* open for writing */ 
     if ( fp1 == NULL )      /* check does file exist etc */
     {
           printf(“Cannot open %s for reading \n”, fname1 );
           exit(1);    /* terminate program */
     }
     else if ( fp2 == NULL )
     {
           printf(“Cannot open %s for reading \n”, fname2 );
           exit(1);    /* terminate program */
     }
     else       /* both files opened successfully  */
     {
           ca  =  getc( fp1 ) ;      
           cb  =  getc( fp2 ) ;

           while ( ca != EOF   &&   cb != EOF   &&   ca == cb  )
           {
                ca  =  getc( fp1 ) ;      
                cb  =  getc( fp2 ) ;
           }
           if (  ca == cb )
                printf(“Files are identical \n”);
           else if ( ca !=  cb )
                printf(“Files differ \n” );
           fclose ( fp1 );           
           fclose ( fp2 );
     }
}


Writing to Files
The previous programs have opened files for reading and read characters from them.

To write to a file, the file must be opened for writing e.g.

        fp = fopen( fname, “w” );

If the file does not exist already, it will be created.  If the file does exist, it will be overwritten!  So, be careful when opening files for writing, in case you destroy a file unintentionally. Opening files for writing can also fail. If you try to create a file in another users directory where you do not have access you will not be allowed and fopen will fail.

Character Output to Files
The function putc( c, fp ) writes a character to the file associated with the file pointer fp.

Example:
              Write a file copy program which copies the file “prog.c” to “prog.old”

Outline solution:

     Open files appropriately
     Check open succeeded
     Read characters from prog.c and
     Write characters to prog.old until all characters    copied

     Close files


The step: “Read characters .... and write ..” may be refined to:

    read character from prog.c
    while not end of file do
    begin
        write character to prog.old
        read next character from prog.c
    end




/* filecopy.c : Copy prog.c to prog.old */

#include <stdio.h>
void main() 
{
    FILE *fp1, *fp2, *fopen();
    int c ;

    fp1 = fopen( “prog.c”,  “r” );       /* open for reading */
    fp2 = fopen( “prog.old”, “w” ) ; ../* open for writing */  

    if ( fp1 == NULL )      /* check does file exist etc */
    {
        printf(“Cannot open prog.c for reading \n” );
        exit(1);    /* terminate program */
    }
    else if ( fp2 == NULL )
    {
        printf(“Cannot open prog.old for writing \n”);
        exit(1);    /* terminate program */
    }
    else        /* both files O.K. */
    {
        c = getc(fp1) ;    
        while ( c != EOF)
        {
            putc( c,  fp2);    /* copy to prog.old */
            c =  getc( fp1 ) ;
        }

    fclose ( fp1 );         /* Now close files */
    fclose ( fp2 );
    printf(“Files successfully copied \n”);
    }
}


The above program only copies the specific file prog.c to the file prog.old. We can make it a general purpose program by prompting the user for the files to be copied and opening them appropriately.

/* copy.c : Copy any user file*/

#include <stdio.h>
void main() 
{
     FILE *fp1, *fp2, *fopen();
     int c ;
     char fname1[40], fname2[40] ;

     printf(“Enter source file:”) ;
     gets(fname1);

     printf(“Enter destination file:”);
     gets(fname2);

     fp1 = fopen( fname1,  “r” );       /* open for reading */
     fp2 = fopen( fname2, “w” ) ; ../* open for writing */

     if ( fp1 == NULL )      /* check does file exist etc */
     {
           printf(“Cannot open %s for reading \n”, fname1 );
           exit(1);    /* terminate program */
     }
     else if ( fp2 == NULL )
     {
           printf(“Cannot open %s for writing \n”, fname2 );
           exit(1);    /* terminate program */
     }
     else       /* both files O.K. */
     {
           c = getc(fp1) ;      /* read from source */
           while ( c != EOF)
           {
                putc( c,  fp2);    /* copy to destination */
                c =  getc( fp1 ) ;
           }

     fclose ( fp1 );            /* Now close files */
     fclose ( fp2 );
     printf(“Files successfully copied \n”);
     }
}





Command Line Parameters: Arguments to main()

Accessing the command line arguments is a very useful facility. It enables you to provide commands with arguments that the command can use e.g. the command

% cat prog.c

takes the argument "prog.c" and opens a file with that name, which it then displays. The command line argumenst include the command name itself so that in the above example, "cat" and "prog.c" are the command line arguments. The first argument i.e. "cat" is argument number zero, the next argument, "prog.c", is argument number one and so on.

To access these arguments from within a C program, you pass  parameters to the function main(). The use of arguments to main is a key feature of many C programs.

 The declaration of main looks like this:

    int main (int argc,  char *argv[])

This declaration states that

1.     main returns an integer value (used to determine if the program terminates successfully)
2.     argc is the number of command line arguments including the command itself i.e argc must be at least 1
3.     argv is an array of the command line arguments




The declaration of argv means that it is an array of pointers to strings (the command line arguments). By the normal rules about arguments whose type is array, what actually gets passed to main is the address of the first element of the array. As a result, an equivalent (and widely used) declaration is:

    int main (int argc,  char **argv)

When the program starts, the following conditions hold true:
o  argc is greater than 0.
o  argv[argc] is a null pointer.
o  argv[0], argv[1], ..., argv[argc-1] are pointers to strings
        with implementation defined meanings.
o  argv[0] is a string which contains the program’s name, or is an
        empty string if the name isn’t available. Remaining members of
        argv are the program’s arguments.



Example: print_args echoes its arguments to the standard output – is a form of the Unix echo command.


/* print_args.c: Echo command line arguments */

#include <stdio.h>
#include <stdlib.h>

int main(int argc,  char *argv[])
{
    int i = 0 ;
    int num_args ;

    num_args = argc ;

    while( num_args > 0)
    {
        printf(“%s\n“, argv[i]);
        i++ ;
        num_args--;
    }
}

If the name of this program is print_args, an example of its execution is as follows:

% print_args hello goodbye solong
print_args
hello
goodbye
solong
%

Exercise: Rewrite print_args so that it operates like the Unix echo command. Hint: You only need to change the printf statement.


The following is a version of the Unix cat command:

/* cat1.c: Display files specified as command line parameters */

#include <stdio.h>
#include <stdlib.h>

int main(int argc,  char *argv[])
{
        int i  = 1 ;
        int c ;
        int num_args = 0 ;
        FILE *fp;

        if ( argc == 1 )
        {
          fprintf(stderr, "No input files\nUsage: % cat file…\n");
          exit(1);
        }

        if ( argc > 1 )
                printf("%d files to be displayed\n", argc-1);

        num_args = argc - 1;

        while( num_args > 0)
        {
             printf("[Displaying file %s]\n", argv[i]);
             num_args--;
             fp = fopen( argv[i], "r" ) ;
             if ( fp == NULL )
             {
                 fprintf(stderr,"Cannot display %s \n", argv[i]);
                 continue; /* Goto next file in list */
             }

             c = getc(fp) ;
             while ( c != EOF )
             {
                     putchar( c );
                     c = getc( fp );
             }
             fclose( fp );
             printf("\n[End of %s]\n--------------\n\n", argv[i]);
             i++;
       }
}

Note: The continue statement causes the current iteration of the loop to stop and control to return to the loop test.
The following is a version of the Unix wc command called count which operates as follows

% count prog.c
prog.c: 300 characters   20 lines

% count –l prog.c
prog.c: 20 lines

% count –w prog.c
prog.c: 300 characters


/*count.c : Count lines and characters in a file */
#include <stdio.h>
#include <stdlib.h>

int main(int argc,  char *argv[])
{
        int c , nc, nlines;
        char filename[120];
        FILE *fp, *fopen();

    if ( argc == 1 )
    {
           fprintf(stderr, "No input files\n");
           fprintf(stderr, "Usage: \% count [-l] [w] file\n");
           exit(1);
     }

        nlines = 0 ;
        nc = 0;

        if ((strcmp("-l", argv[1]) == 0)  ||
            (strcmp("-w", argv[1]) == 0) )
                        strcpy(filename, argv[2]) ;
        else
                        strcpy(filename, argv[1]);

        fp = fopen( filename, "r" );

        if ( fp == NULL )
        {
          fprintf(stderr,"Cannot open %s\n", filename );
          exit(1);
        }
   c = getc( fp ) ;
        while (  c != EOF )
        {
                if ( c  ==  '\n')
                nlines++ ;
                nc++ ;
                c = getc ( fp );
        }

        fclose( fp );

        if ( strcmp(argv[1], "-w") == 0 )
                printf("%s: %d characters \n", filename, nc );
        else if ( strcmp(argv[1], "-l") == 0 )
          printf("%s: %d lines \n", filename, nlines );
        else
          printf("%s: %d characters  %d lines\n", filename, nc, nlines );

Logical OR is represented by || in the code above. Logical AND is represented by && in C.

The function strcpy() is one of many library string handling functions. It takes two strings as arguments and copies the second argument to the first i.e. it operates as a form of string assignment. In C you CANNOT assign strings as:

filename = "prog.c"  /* WRONG */

strcpy( filename, "prog.c");   /* CORRECT */

The function strcmp() is another string handling function. It takes two strings as arguments and returns 0 if the two strings are the same. As for assignment, you cannot test string equality with == i.e.

if (filename == "prog.c")  /* WRONG */

if (strcmp(filename,"prog.c")==0)  /* CORRECT */

Note: The above program crashes if you run it as:

% count –w
or
% count –l

This is because in these cases we failed to test if there was a 3rd argument containing the filename to be processed. We simply try to access this non-existent argument and so cause a memory violation. This gives rise to a so-called "bus error" in a Unix environment.

As an exercise, insert code to correct this failure.

Exercise: Write a copy command to operate like the Unix cp command that takes it files from the command line:

% copy file newfile