## Saturday, August 27, 2011

### How to open website using C

You can easily open your website using C. You can pass the your website url as argument. When you run the code, this will open the url in browser. The code is very simple. You have to include <stdlib.h> or <windows.h> to use it.

#include<windows.h>int main(){    system("explorer http://www.programming-technique.blogspot.com");    return 0;}

### How to change the text color of console using C

The following code changes the text color of console to the color defined by color value supplied. You must include <windows.h> to use this function. It works on windows only.

#include <stdio.h>#include <windows.h>#include <conio.h>void SetColor(int ForgC){     WORD wColor;     HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);     CONSOLE_SCREEN_BUFFER_INFO csbi;     if(GetConsoleScreenBufferInfo(hStdOut, &csbi))     {          wColor = (csbi.wAttributes & 0xF0) + (ForgC & 0x0F);          SetConsoleTextAttribute(hStdOut, wColor);     }     return;}int main(){  int fore;  printf("Enter text color value: ");  scanf("%d",&fore);  SetColor(fore);  printf("Your color will be like this");  getch();  return 0;}

Output

### How to change Background and Foreground color of Console in C

<windows.h> provides various functions to change the properties of windows like changing color, resizing windows, changing cursor position etc. The source code for changing the background and foreground color of console is given below. You can pass different color values to the function to get different color in background and foreground.

#include <stdio.h>#include <windows.h>#include <conio.h>void SetColorAndBackground(int ForgC, int BackC){     WORD wColor = ((BackC & 0x0F) << 4) + (ForgC & 0x0F);;     SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), wColor);     return;}int main(){  int fore, back;  printf("Enter foreground and background color values: ");  scanf("%d%d",&fore, &back);  SetColorAndBackground(fore,back);  printf("Your color will be like this");  getch();  return 0;}

Output

### gotoxy() function in Code::blocks(gcc compiler) using C

In Turbo C/C++ and Borland C++ compiler, gotoxy() is build in function. You need not have to write its function definition. All you have to do is call the function with arguments as x and y coordinate. But in modern C compiler like gcc and IDE Code::Blocks, gotoxy() is not  build-in function, you have to define it before use them. The following code is the function definition for gotoxy(). Remember: This function only works on windows, because the function definition includes functions of header file “windows.h”. So to use gotoxy() you must include “windows.h”.

COORD coordinate = {0,0}; //initializationvoid gotoxy(int x, int y){ //function definition   coordinate.X = x; coordinate.Y =  y;   SetConsoleCursorPostion(GetStdHandle(STD_OUTPUT_HANDLE),coordinate);}

NOTE: coordinate (0,0) is left-top corner of your window.

### Returning Two Dimensional Array from a Function in C

Many author do not include topics about returning array from a functions in their books or articles. It is because, in most  of the cases, there is no need of array to be returned from a function. Since, on passing array by its name, the address of its first member is passed and any changes made on its formal arguments reflects on actual arguments. But sometimes, there may arise the situation, where an array have to be returned from a function, for example, multiplying two matrices and assigning the result to another matrix. This can be done by creating a pointer to an array. The source code of returning two dimensional array with reference to matrix addition is given here.

#include <stdio.h>int (*(Matrix_sum)(int matrix1[][3], int matrix2[][3]))[3]{    int i, j;    for(i = 0; i < 3; i++){        for(j = 0; j < 3; j++){            matrix1[i][j] = matrix1[i][j] + matrix2[i][j];        }    }    return matrix1;}int main(){    int x[3][3], y[3][3];    int (*a)[3]; //pointer to an array    int i,j;    printf("Enter the matrix1: \n");    for(i = 0; i < 3; i++){        for(j = 0; j < 3; j++){            scanf("%d",&x[i][j]);        }    }    printf("Enter the matrix2: \n");    for(i = 0; i < 3; i++){        for(j = 0; j < 3; j++){            scanf("%d",&y[i][j]);        }    }    a = Matrix_sum(x,y); //asigning    printf("The sum of the matrix is: \n");    for(i = 0; i < 3; i++){        for(j = 0; j < 3; j++){            printf("%d",a[i][j]);            printf("\t");        }        printf("\n");    }    return 0;}

### Mini project Employee record system using C

The employee record system is very simple and for very beginner mini project. It is based one the menu-driven program for elementary database management. It employ all the basic technique of file handling in C. It consists of following features
• Writing the data in binary file
• Reading the data from binary file
• Modify the record
• Delete the record
This project is a learning milestone for beginner who want to step into the database management project in C.
Source Code
/**
*  A menu-driven program for elementary database management
*  @author: Bibek Subedi
*  @language: C
*  This program uses file handling in Binary mode
*/

/// List of library functions
#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
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

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
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;
}


Output

### Binary Vs Text File in C

From the programming angle there are three main areas where text and binary mode files are different. These are:

• Handling of newlines
• Representation of end of file
• Storage of numbers

Let us explore these three differences:

In text mode, a newline character is converted into the carriage return-linefeed combination before being written to the disk. Likewise, the carriage return-linefeed combination on the disk is converted back into a newline when the file is read by a C program. However, if a file is opened in binary mode, as opposed to text mode, these conversions will not take place.

The second difference between text and binary modes is in the way the end-of-file is detected. In text mode, a special character, whose ASCII value is 26, is inserted after the last character in the file to mark the end of file. If this character is detected at any point in the file, the read function would return the EOF signal to the program. As against this, there is no such special character present in the binary mode files to mark the end of file. The binary mode files keep track of the end of file from the number of character present in the directory entry of the file.

The last difference is storage of numbers. In text file the text and characters are stored one character per byte, as we expect. But numbers are stored as strings of characters. Thus, 65112, even though it occupies 4 bytes in memory, when transferred to the disk using fprintf(), would occupy 5 bytes, one byte per character. Here if large amount of data is to be stored in a disk file, using text mode may turn out to be insufficient. The solution is to open the file in binary mode and use those functions (fread() and fwrite()) ) which store the numbers in binary format. It means each number would occupy same number of bytes on disks as it occupies in memory.

### Writing into and reading from a binary file in C

In previous example, you learn how to write and read a text file in C. If the number of fields in the structure increase, writing structures using fprintf(), or reading them using fscanf(), becomes quite clumsy. The more efficient way of writing records(structures) can be achieved by the use of two functions fread() and fwrite(). The fwrite() functions writes whole structures at a time and fread() function read all the fields at a time.

Writing into the binary file

The following code segment illustrates how to write data into file in binary format.

struct emp{   char name[20];   int age;   float bs;};struct emp e;fp = fopen("EMP.DAT","wb");if(fp == NULL){   puts("Cannot open file");}printf("Enter name, age and basic salary");scanf("%s%d%f",e.name,&e.age,&e.bs);fwrite(&e,sizeof(e),1,fp);fclose(fp);}

The following code segment illustrates how to read data from file in binary format.

fp = fopen("EMP.DAT","rb");while(fread(&e,sizeof(e),1,fp)==1){   printf("%s %d %f\n",e.name,e.age,e.bs);}fclose(fp);

## Tuesday, August 23, 2011

### Writing into and reading from a text file in C

We use fprintf() and fscanf() functions to write into the file and read from file respectively. fprintf()  writes the data to the text file and fscanf() reads the data from from file. The following example illustrates the concept….

Writing into the text file

#include<stdio.h>#include<stdlib.h>int main(){    FILE *fp;    struct emp{        char name[40];        int age;        float bs;    };    struct emp e;    //opening file in writing mode    //this code creates a file named employ.dat if    //it is not created or writes on the file if it    //is already created.    fp = fopen("employ.dat","w");    if(fp == NULL){ //if file is not opened        puts("Cannot open file");        exit(1);    }    printf("\nEnter name, age and basic salary: ");    scanf("%s %d %f", e.name, &e.age, &e.bs);    //writes name age and basic salary to the file    fprintf(fp, "%s %d %f\n", e.name, e.age, e.bs);    fclose(fp); //close the file    return 0;}

#include<stdio.h>#include<stdlib.h>int main(){    FILE *fp;    struct emp{        char name[40];        int age;        float bs;    };    struct emp e;    //opening file in writing mode    //this code try to open the employ.dat    //if it is already existed and returns null    //to fp it is not existed    fp = fopen("employ.dat","r");    if(fp == NULL){ //if file is not opened        puts("Cannot open file");        exit(1);    }    printf("\nThe name, age and basic salary are: ");    //search the file until end of file encountered    while(fscanf(fp, "%s %d %f\n", e.name, &e.age, &e.bs)!=EOF){        printf("%s %d %f\n",e.name,e.age,e.bs);    }    fclose(fp); //close the file    return 0;}

### C Programming: File Handling

The console function like printf() and scanf() have been used for input/output .This scheme is adequate if the volume of data involved in not so large or it is not necessary to store the information for further use. However, many applications may require a large amount of data to be read, processed, and also saved for later use. Such information is stored on the auxiliary memory device in the form of data file.And a file is a collection of bytes that is given a name. In most computer systems, files are used as a unit of storage primarily on floppy-disk or fixed-disk data storage system (or they can be CDs or other storage device). Thus data files allow us to store information permanently, and to access and alter that information whenever necessary. The file handling function available in standard library in order to implement I/O midel is classified as follows:

a) File access

b) Operation input/output

c) Formatted input/output

d) Character input/output

e) Direct input/output

f) File positioning

g) Error handling

The file access included the function like fopen() to open a file, fclose() to close a file , fflush () to flush out the buffer associated with a file, and freopen() to change the file associated with a stream. Also setvbuf() and setbuf() functions are use to allow the users explicitly control the file buffering strategy. The operation on file includes like remove() to remove a file, rename() to rename a file ,tempfile() to create a temporary binary file and tmpnam() to generate a unique filename. Formatted input/output group includes the n functions fscanf(), scanf() and sscanf() to read formatted data. Similarly fprintf() ,printf(), sprint(), vfprintf(), vprintf() and vsprintf() to write formatted data. The character input/output group includes the functions fgetc() ,getc() and getchar() to read a character from an input stream and functions ungetc() to push back a character to an input stream. The functions fgets() and gets() are to read strings and the output functions fputc(),putc(), putchar(), fputs() and puts() are also included in this group. The direct input/output group includes functions fread() to read and fwrite() to write a certain number of data items specified size. File positioning group includes functions fread() to read and fwrite() to write a certain number if data items specified size. File positioning group includes functions to set the file positon to some specified value to allow access to a specific portion of the seek(),interrogate the current file position ftell(),and reset the file position to the beginning of the file rewind(). Error handling group include functions to test whether EOF returned by a function indicates an end-of-file or an error (feof and ferror), clear end-of-file and indicators clearer, and map the error number errno to an error message perror.

File Accessing:-

To work with file using any file handling library functions, C requires a pointer to structure FILE defined in <stdio.h>.The declaration of file pointer is done as follows:

FILE *fptr;

This declaration creates a variable fptr, which is pointed to the FILE structure. The pointer to the FILE structure is also called file pointer. The FILE structure describes the current state of a file such as file status flag, file descriptor, file buffer etc. There are also predefined file pointers such stdin, stdout, and stderr which refers to standard input (normally keyboard), standard output (normally monitor) and standard error (connected to screen for error handling). The file access functions provide the facilities to open and close a file, flush out the file buffer, change the file content and control the file buffering strategy. Before working with a file it should be opened first. To open a file and associate it with a stream, we use fopen().Its prototype is shown here:

FILE *fopen(char *fname,char *mode);

The fopen() function, like all the file-system functions ,uses the header <stdio.h> .The name of the file including the path is specified by fname and the mode specifies how file is accessed. Both of these parameters are string. The string specifying the mode is shown in following table.

 S.N Mode Meaning 1 "r" Open a text file for reading 2 "w" Create a text file for writing 3 "a" Append to a text file 4 "rb" Open a binary file for reading 5 "wb" Open a binary file for writing 6 "ab" Append to binary file 7 "r+" Open a text file for read/write 8 "w+" Create a text file for read/write 9 "a+" Append or creat a text file for read/write 10 "r+b" Open a binary file for read/write 11 "w+b" Create a binary file for read/write 12 "a+b" Append a binary file for read/write

### Difference between Arrays and Structures in C

Both the arrays and structures are classified as structured data types as they provide a mechanism that enable us to access and manipulate data in a relatively easy manner. But they differ in a number of ways listed in table below:

 Arrays Structures 1. An array is a collection of related data elements of same type. 1. Structure can have elements of different  types 2. An array is a derived data type 2. A structure is a programmer-defined data type 3. Any array behaves like a built-in data types. All we have to do is to declare an array variable and use it. 3. But in the case of structure, first we have to design and declare a data structure before the variable of that type are declared and used. 4. Array allocates static memory and uses index / subscript for accessing elements of the array. 4. Structures allocate dynamic memory and uses (.) operator for accessing the member of a structure. 5. Array is a pointer to the first element of it 5. Structure is not a pointer 6. Element access takes relatively less time. 6. Property access takes relatively large time.

### Adding two complex numbers using Structure in C

Simple algebraic addition do no work in the case of Complex Number. Because they have two parts, Real and Imaginary. To add two complex numbers, real part of one number must be added with real part of other and imaginary part one must be added with imaginary part of other. The concept of complex number can be viewed as structure having two members real and imaginary. So to add two complex numbers we use structure addition. If complex1 and complex2 be two structure variables and complex3 be their sum then

complex3.real = complex1.real + complex2.real;complex3.imag = complex1.imag + complex2.imag;

In this way, we can add two complex numbers. The source code and output of the program is given here…
Source Code:
#include<stdio.h>struct comp{    float real;    float imag;};struct comp comp1,comp2;struct comp sum_complex(struct comp complex1,struct comp complex2){    struct comp temp;    temp.real = complex1.real + complex2.real;    temp.imag = complex1.imag + complex2.imag;    return temp;}int main(){    struct comp result;    printf("Enter Complex Number 1: ");    scanf("%f%f",&comp1.real, &comp1.imag);    printf("Enter Complex Number 2: ");    scanf("%f%f",&comp2.real,&comp2.imag);    result = sum_complex(comp1,comp2);    printf("The sum is %.2f + i%.2f\n\n", result.real,result.imag);    return 0;}

Output

### Electricity Billing System using Structures in C

This example illustrates the concept of structures discussed in previous post. Here structure variable bill is declared which has structure template Bill and members firstName, lastName, Address, previousUnit and presentUnit. The structure represents the information of a customer and the program calculates the cost by checking previous and present unit. After you understand the code you will have the knowledge of following things:

1. Defining Structure
2. Declaring Structure variable
3. Accessing members of structure
4. Passing structure in function
5. Returning structure from function

The source code and output is given here…

Source Code

//generating electricity bill using structure in C#include<stdio.h>/** This block defines the structure Bill having    fields for first name, last name, address,    previous unit and present unit. The structure    must be defined before main function */struct Bill{    char firstName[10];    char lastName[10];    char Address[20];    float previousUnit;    float presentUnit;};/** This is the function definition that    calculates the cost. Here structure is passed    as an argument */float generateBill(struct Bill temp){    float diff;    diff = temp.presentUnit - temp.previousUnit;    if(diff > 20){        return diff*4.75;    }else{        return 20*4.75+(diff-20)*7.75;    }}int main(){    struct Bill bill; /*Declaration of structure variable*/    printf("Fill up the following: \n");    printf("First Name: ");    gets(bill.firstName); //accessing member    printf("Last Name: ");    gets(bill.lastName);    printf("Address: ");    gets(bill.Address);    printf("Previous Unit: ");    scanf("%f",&bill.previousUnit);    printf("Present Unit: ");    scanf("%f",&bill.presentUnit);    printf("\a\n\n***********Electricity Bill***************\n\n\a");    printf("Name: %s %s",bill.firstName,bill.lastName);    printf("\nAddress: %s",bill.Address);    printf("\nPrevious Unit: %.3f       Current Unit: %.3f",bill.previousUnit,bill.presentUnit);    printf("\nCost: %.3f\n\n", generateBill(bill));    return 0;}

Output

### C Programming: Structures

We know that array is a collection of data that represent same data type. We cannot make array that has data with different types using a single name. Fortunately, C supports a constructed data type called structures a mechanism for packing data of different types. A structure is a convenient tool for handling a group of logically related data items. For example, it can be used to represent a set of attributes, such as student_name, roll_number and marks. The concept of a structure is analogous to that of a ‘record’ in many other languages.

Defining a structure

Unlike arrays, structures must be defined first for their format they may be used later to declare structure variable. structure definition is the template of structure variable. The general format of a structure definition is

struct tag_name{   data_type    member1;   data_type    member 2;   - - - - -    - - - - };
Declaring structure variable
After defining a structure format you can declare variables of that type. A structure variable declaration is similar to the declaration of variable of any other types. It includes the following elements:

• The keyword struct

• The structure tag name

• List of variable names separated by commas.

• A terminating semicolon
The general syntax is
struct tag_name variable1, variable2, variable3,...,variableN;

Example
  1: struct student{  2:    char name[10];  3:    int roll_no;  4:    float marks;  5: };  6:   7: struct student student1;

In this example line numbers 1-5 is structure definition. A structure is defined with tag_name student having members name, roll_no and marks. This is only template for structure variable. Remember members themselves are not variables. They do no occupy any memory until they are associated with the structure variables such as student1 in above example. Till line 7 no variable is created and structure definition cannot do anything without variable. Line 7 declares a structure variable student1 which has fields name, roll_no and marks. If you declare another variable like student2 then it also includes those fields(members).

Accessing structure members

We can access and assign values to the members of a structure in a number of ways. As mentioned earlier, the members themselves are not variables. They should be linked to the structure variables in order to make them meaningful members. The link between a member and a variable is established using the member operator ‘.’which is also known as ‘dot operator’ or ‘period operator’. For example, student1.marks is the variable representing the marks of student1 and can be treated like any other ordinary variables.

## Wednesday, August 17, 2011

### Sorting strings alphabetically using C

Source Code

#include<stdio.h>#include<string.h>#include<stdlib.h>void reorder(int n, char *x[]);int main(){    int i , no_string;    char *x[10];    printf("Enter the no of strings: ");    scanf("%d",&no_string);    printf("Enter the strings: \n");    for(i = 0; i < no_string; i++){        x[i] = (char*) malloc (12*sizeof(char));        printf("string %d: ",i+1);        scanf("%s", x[i]);    }    printf("The sorted strings are: ");    reorder(i,x);    for(i = 0; i < no_string; i++){        printf("\nstring %d: %s", i+1, x[i]);    }    return 0;}void reorder(int n, char *x[]){    char *temp;    int i,item;    for(item = 0; item < n-1; ++item){        for(i = item+1; i < n; ++i){            if(strcmp(x[item],x[i]) > 0){                temp = x[item];                x[item] = x[i];                x[i] = temp;            }        }    }    return;}

Output