Google Find us on Google+

Tuesday, 2 July 2013

Structures

Introduction:

Structure is a function which stores the block of memory. However, arrays also stores the memory, but they have limitation that they contains same type of data(i.e, only integer type functions or character type etc...).
Some times we require a data structure that can store data items of mixed data type. Certain items are made up of different variables and different members of different data types(i.e, all kinds of data types-integers, characters, float etc...).
For example, a bank accountant contains his name, Id, and his date of joining etc... These three were of different kinds of data types. Name is defined by character data type, Id is defined by long int data type, and date of joining is defined by integer data type. 

 Member

 Data type
Name

ID

DOJ
Char

Long int

int

The collective information about an accountant is known as a "structure". precisely, a structure can be defined as "a group of data types of different members."
Here, Name, id, and date of joining are the members of a structure. Each member is a variable that can be referred to through the name of the structure. Variable form a group under a single name for ease of using and handling of same.  
Variable
Member
Data type
b1
name, id, DOJ 
char, long int, int
b2
name, id, DOJ 
char, long int, int

For example, consider a bank accountant structure. Let us assume that the structure defined by a name "Bank"[Don't get confused by the name of the structure and by the name of bank accountant. They both differ each other. Since structure contains all the details of the bank accountant, so bank accountant name is one kind of member of the structure and that structure has a name, defined by the user]. Suppose if there are three banks, then we need to declare three names to identify separately, since all the three banks contains names of the accountant, id etc...Assume Bank1 is declared as b1; Bank2 as b2; Bank3 as b3. Therefore b1, b2, b3 are known as variables of the stucture "Bank". The number of variables and members depends on the user's declaration. 

Defining a structure with its keyword:

A structure is defined by a keyword struct. Strcut is followed by the name of the structure and the body of the structure which is enclosed with in curly braces. Whole body contains the declaration of its members. And each member must and should contain the user defined data type(i.e; int, char, float,....). Defining a structure ends by a semicolon. 
Structure is declared by the below given syntax: 
struct <name>
{
    data type member1;
    data type member2;
    data type member3;
    .
    . 
    .
};
For example consider the following structure's definition:
struct Bank
{
  char e_name[10];
  long int Id;
  int DOJ;
};
Here, struct is a keyword(obviously it is compulsory for each and every structure to define). Bank is an identifier or else it can be known as structure's tag name, and also known as user-defined type, since it is given by the user(programmer). The body of the structure contains three members, they are of:
  •  e_name to store the name of the employer since name contains characters, it is declared by 'char' data type. 
  • Id to store the id of an employer, since it has all the integer values with long number of digits, so it is declared by 'long int' data type.
  • DOJ to store the date of joining, since it has only integer values, so it is declared by 'int' data type.
Definition doesn't reserve any memory space, but the members we declared in different data types will store some memory according to the bytes. It define in what way and how much information we can store according to the user.
A point to be noted: The same member names can occur in different structures.

Declaring a structure variable:

If a structure is declared, then we can declare variables and members to store the information. variables are specially known to store the information of particular structure type. Simply we can  
say that a file does a work to store all the details provide by the user. In the same way the variable does to store the information(i.e; members). When a structure definition is placed in-front of the program code(i.e; global area), it will be visible to all the functions in the program. In the case, we can declare variables of type structure in global area or with in any function as local variables.
Declaring a variable of type Bank:
struct Bank b1;
This statement can be used in any function. 
Once a variable is declared, memory equivalent to total of memory required by individual members of structure Bank is allocated to b1.
Two points to be noted:
1. If we want structure variables to be local to a function, we have to define structure with in that function. In that case, structure becomes local to that function and would not be accessible to other functions.
2. If we give this definition at global place, then the structure variables become global and would be accessible to all functions which is again not recommended.
We can declare a variable in two methods:
1.  struct Bank 
     {
       char e_name[20];
       long int Id;
       int DOJ;
     }b1,b2,b3;

2.  struct Bank 
     { 
        char e_name[20];
        long int Id;
        int DOJ;
     };
     void main() 
     struct Bank b1;
     struct Bank b2;
     struct Bank b3;
A point to be noted: Tag name is compulsory in the 2nd method. Variable should be declared with its keyword struct and its <tag name>.
Here, struct is constant, and tag name is optional to the user.
Diagrammatic representation of allocating memory to the structure variable b1:


A point to be notedStructure variables will allocate members in continuous memory locations.
Therefore b1 reserves the sum of the memory bytes declared by the individual members(i.e, 20+4+2=26 bytes).

Declaring values to structure members:

Between structure variable name and member name a dot operator is used to access a structure.
The syntax is given below:
structure_variable_name.member_name
For example consider the below given statements:


  • Suppose if we want input all the details of an employer who is from Bank1.                Therefore declaring values will be like:                                                             gets(b1.e_name);                                                                                            scanf("%d",&b1.Id);                                                                                   scanf("%d",&b1.DOJ);
  • If we want to print the values then the statements would be like:                     puts(b1.e_name);                                                                                                        printf("%d",b1.Id);                                                                                         printf("%d",b1.DOJ);                 

A sample program code based on the functions which we have been discussed till now:
              
simple C program structure to input and output the data
#include<conio.h>
#include<stdio.h>
struct Bank
{
  char e_name[20];
  long int Id;
  int DOJ;
};
void main()
{
struct Bank b1;
printf("enter the details of an employer");
printf("\n enter the name of the employer:");
gets(b1.e_name);
printf("enter the Id:);
scanf("%ld",&b1.Id);
printf("enter date of joining:");
scanf("%d",&b1.DOJ);
printf("\n employer's details");
printf("\n Name of an employer is");
puts(b1.e_name);
printf("\n Id of an employer is %ld",b1.Id);
printf("\n Date of joining of an employer is %d",b1.DOJ);
getch();
}

Output:
enter the details of an employer 
enter the name of an employer: Raj
enter the Id: 12100
enter date of joining: 2
employer's details
Name of an employer is Raj
Id of an employer is 12100
Date of joining of an employer is 2

Initializing a structure:

Like any other data type we can initialize structures when we declare variables of structure. We can provide initialization values separated by comma with in pair of curly braces. The order of values must match with the order of members declared in the structure definition.
A point to be noted: Data type of the member must be declared in the structure only. And the structure declaration is compulsory. 
For example, 
struct Bank b1={"Raj",12100, 2};
The initialization of each and every member is as following:
e_name field of name is initialized to "Raj",
Id is initialized to 12100,
DOJ is initialized to 2.

Nested Structure:

The structure inside a structure is known as "nested structure". Simply we can say that nested structure is known when structure acts as a member of another structure. This system can be used to create complex data type structures.
For example, we are required to store information about student such as the name, roll_no. , marks, and date of birth. All of these members act as individual elements except date of birth which is made up of three members, via. day, month, and year. So we can define structure date that itself act as a member of structure student as below. 
struct DOB 
{
  int d;
  int m;
  int y;
};
struct student 
{
  char name[10];
  int rank;
  int marks;
  struct DOB dob;
};
Here is an another way to access the structure DOB inside the structure student. It exists with in the scope of the structure student. 
struct student 
{
  char name[10];
  int rank;
  int marks;
  struct DOB
  {
    int d; 
    int m;
    int y;
  }dob;
}s1;
The members of nested structures are accessed from outermost variable to innermost variable with the help of dot (.) operators. 
Also here is another way to define the variable of structure student. Directly we can define as given above, orelse we can use a statement such as struct student s1;
struct student 
{
  char name[10];
  int rank;
  int marks;
  struct DOB
  {
    int d; 
    int m;
    int y;
  }dob;
};
void main()
struct student s1;
Therefore the following statements are illustrated to initialize  the member of structure DOB:
s1.dob.d=24;
s1.dob.m=12;
s1.dob.y=1994;
And if you are willing to initialize only for student members, then the statement would be like:
s1.name="Raj";

We can use more levels of nested structure and access the members of nested structure in the same way from outermost variable to innermost variable names with the help of dot operator. 

Initialization of Nested Structure

If a member of  structure is itself a structure, then initialization values of that structure is enclosed with in curly braces.
The following code initializes variable s1 of type student:
struct student s1={"Raj", 32, 680, {24, 12, 1994}};

Array of structures:

In real life, we need to work on number of files like storing the data of accountants, students, employee etc... In that case, we need to create number of variables of type employer, student etc... Here is an easy way to access these variables as an array.
For example, we can create 20 elements array of type employer as below:
struct employer e[20];
Here, 20 contiguous memoryy blocks are reserved to store information for 20 employee. Each block is divided into a set of members declared in the structure. We can work on 20 employee referring to their variable e followed by an index, by a dot operator, and ending with structure member like:
puts(e[i].name);
printf("%ld", e[i].Id);
scanf("%d" , &e[i].DOJ);
We can also initialize the array structure directly.
struct Bank b[5]={{"Raj", 12100, 2},
                                 {"Ravi", 12101, 3},
                                 {"Rahul", 12102, 4},
                               };

From site : http://ctechrockz.blogspot.com/

Monday, 24 June 2013

Simple C Programs Based On File Handling.

**Program which replaces a particular character in the file with another character. In case the character repeats then only the last occurrence is replaced.**

#include<stdio.h>
#include<conio.h>
int main()
{
    FILE *fp;
    int pos;    //Opening the file in the write mode.
    fp=fopen("srecord.txt","w");
    if(fp==NULL)
    printf("\nError");
    char str[]="Sample String in a File";
    char c,c1,c2;  //Writing to the file using fputs
    fputs(str,fp);
    fflush(fp);
    printf("\nEnter character you want to search");
    scanf("%c",&c1);
    printf("\nEnter character you want to modify");
    fflush(stdin);
    scanf("%c",&c2);   //Taking the file pointer to the beginning of the file
    rewind(fp);   //Reading the file character by character till the EOF.
    while((fscanf(fp,"%c",&c))!=EOF)
    {
    //Store the position with the match
    if(c==c1)
    pos=ftell(fp)-1;
    }
    //Take the file pointer to the beginning.
    rewind(fp);   //Position the file pointer at the replacement point
    fseek(fp,pos,0);     //Printing other character at its place
    fprintf(fp,"%c",c2);   //Taking the pointer to the beginning
    rewind(fp);
    printf("\nContents of the file are ");   //Printing the contents on the screen
    while((fscanf(fp,"%s",str))!=EOF)
    printf("%s ",str);    
    fclose(fp);    //Closing the file.
    getch();
}    


Program 2: Reading and writing data in to the file using structure.

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>  //Creating structure
struct student
{
char name[20];
int rollno;
float marks;
};
void Write();
void Read();  
FILE *fp;   //File stream pointer
int count;
//Structure Variable which will be read and written
struct student s1;
int main()
{
int ch;
while(1)
{
printf("\n1.Write Data");
printf("\n2.Read Data");
printf("\n3.Exit");
printf("\nChoice");
scanf("%d",&ch);
if(ch==1)
{
Write();
}
if(ch==2)
{
Read();
}
if(ch==3)
exit(0);
}
}
void Write()
{
count++;
//Open the file in a+ mode so as to read and write data to the file
fp=fopen("K1201.txt","a+");
printf("\nName:- ");
fflush(stdin);
gets(s1.name);
printf("\nRoll Number:- ");
scanf("%d",&s1.rollno);
printf("\nMarks:- ");
scanf("%f",&s1.marks);
//Use the fwrite function to write the data to the file
fwrite(&s1,sizeof(struct student),1,fp);
//Close the file after writing the data
fclose(fp);
}
void Read()
{
int i;
//Open the file in a+ mode so that we can read and write the data
fp=fopen("K1201.txt","a+");
for(i=0;i<count;i++)
{
//Read all the records from the file one by one. We are reading an entire
//structure variable one at a time
fread(&s1,sizeof(struct student),1,fp);
printf("\nName:- %s",s1.name);
printf("\nRoll Number:- %d",s1.rollno);
printf("\nMarks:- %f",s1.marks);
}
//Closing the file
fclose(fp);
}




From site : http://ctechrockz.blogspot.com/

Sunday, 2 June 2013

On Software Systems.

 A Brief Discussion About Software Systems:

System software consists of programs that which manages the hardware resources of a computer. And it performs the required tasks. These programs are further classified to three categories:
System support, System development, and the Operating system.

Operating Systems:

The Operating systems provides services such as user interface, files, and data base access. And also interface to  communication systems such as Internet Protocols. The primary purpose of this operating system's software is to keep the system operating in an efficient manner.

System Support:

The System software provides system utilities and other operating services. Examples are of sort programs and disk format programs. Operating services consists of programs that provide performance statistics for the operational staff and security monitors to protect the system and the data.

System Development Software:

The System development software includes the language translation that convert programs into machine language for execution, debugging tools to ensure that the programs are error free and Computer Assisted Software Engineering(CASE)systems.

From site : http://ctechrockz.blogspot.com/

On Software Applications.

Software Applications:

Same as like System Software's, Application Software is also classified into two categories:
General Purpose Software, and the Application Specific Software.

General Purpose Software:

It is purchased from Software developers and it can be used for more than one application. Word processors, Data Base Management Systems, and Computer Aided Designing or Drafting Systems comes under these software systems.

Application Specific Software:

It can be used only for its intended or achieving purposes. A general ledger(i.e. a book in which a company or organization write downs the amount of money it spends and receives) system used by accounts and a material requirement planning systems used by a manufacturing organization are examples of Application Specific Software. They can be used only for the task for which they are designed.

From site : http://ctechrockz.blogspot.com/

Thursday, 30 May 2013

About Machine Language And High Level Languages.

Machine Language:

The only language that can be understood by the computer hardware is the Machine Language.
The instructions in machine language must be in streams of 0's and 1's. Because the internal circuits of a computer are made up of switches, transistors, and other electronic devices that can be one of two states: off or on
The off state is represented by 0,and the on state by 1.

High Level Language:

The desire to improve programmer efficiency and to change the focus from the computer to the  problem being solved led to the development of High Level Languages. They must be converted to machine language. The process of converting high level language to machine language is known as Compilation. Each and every programming language uses a piece of software, called a Compiler or an Interpreter, to translate the program code into the machine language.
The first widely used high level language is FORTRAN-was created by John Backus and an IBM team in 1957; it is still widely used today in scientific and engineering applications. 
After the invention of FORTRAN, with in a short span of time COBOL-was invented by Admiral Hopper.
FORTRAN-is an acronym for FORmula TRANslation.
COBOL-is an acronym for COmmon Business Oriented Language.

Thursday, 25 April 2013

Input Output Operations getc() And putc() Of Files.

The standard input/output library provides similar routines for file input/output as well as for standard input/output.

getc() and putc()

The two functions getc() and putc() are the most basic functions of C. They are used to read the character and to display the character.

getc():

The function getc() reads a character from a file referenced by file pointer opened in read mode using fopen(). The syntax of getc() is: int getc(File's pointer); 
Example: int getc(fp); 
getc() returns the next character on the given input stream and increments the stream's file pointer to the next character. It reaches EOF marker after reaching the end of  file.

putc():

The function putc() writes a character to the file which is opened by fopen() in write mode. 
The syntax of putc() is: int putc(int c,fp);
putc() outputs the character given by 'c' to the file through the pointer 'fp'. It returns the character 'c' on success, that is, when a character is written to that particular which we have been opened. On error, the pointer will points towards end of the file(EOF).

The character input/output operations like getchar(), and putchar() will also work as similar to getc(fp), and putc(c,fp) 

Example Program:
A program code using getc(), and putc() operations. 
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
void main()
{
FILE *fp;
int c;
fp=fopen("cse.txt","r");  // opens file 'cse' in read mode.
if(fp==NULL)
{
printf("cannot open the file");
exit(0);  //terminates the program.
}
 c=getc(fp);  // reads a character and fp points to the next character.
while(c!=EOF) // checks whether end of file reaches are not; if not the below code will executes.
{
putchar(c); // prints a character 'c' on the screen.
c=getc(fp); // reads next character.
}
fclose(fp); //closes the file which is referenced by the pointer fp.
getch();

Explanation:
In this program, the file named cse.txt is opened in a read mode. Its contents are read character by character using getc(), and then displayed on the screen. When the pointer reaches to EOF, then the while loop terminates and file will be closed using the function called fclose().


From site : http://ctechrockz.blogspot.com/

Sunday, 21 April 2013

Opening And Closing A Data File.

Files are not only used for data, but our programs are also stored in files. To work with a file, a program has to go through the following steps:
  1. Open a file for reading or writing.
  2. Do operation read or write to file using library functions.
  3. Close the file may be used by some other program.
The difference between working with file or with standard input/output terminals is that we must specify the location of file to work within our program.

Opening a File:

Specifying the file you wish to use is referred to as opening the file. When working with a stream oriented data file, the first step is to establish a buffer area,where information is temporarily stored while being transferred between the computer's memory and the data file. The buffer area allows information to be read from or written to the data file more rapidly than would other wise be possible.

Buffered input/output:

A buffer is a region of memory used to temporarily hold data while it is being moved from one place to another. Typically the data is stored in buffer(i.e.memory location) as it is retrieved from an input device (such as a keyboard) or just before it is sent to an output device (such as monitor). 
The buffer area is used using the pointer to FILE declared as:
FILE *ptvar;
where,
FILE (only uppercase letters should be required) is a special structure type that establishes the buffer area, and ptvar is a pointer variable that indicates the beginning of the buffer area(courser). It is often referred to as stream pointer, or simply a stream. The structure type FILE is defined within a system include file, typically stdio.h.

A data file must be opened before it can be created or processed. A file is opened by call to function fopen() which is available in library stdio.h.
The syntax of function fopen() is
ptvar=fopen(file name, file type);
where file name and file type are the stings that represent the name of the data file and the manner in which the data file will be utilised. It means that the file type is just a mode which specifies the purpose of opening a file; reading a file, or writing a file, or appending text at the end of the file(i.e.continuation of writing at the end of the file), etc.
The name chosen for the file must be consistent with the rules for naming files, as determined by the computer's operating system.
The function returns a pointer to the object which controls the stream associated with the file, that is, the pointer to the beginning of buffer area associated with the file(if the file is opened successfully), otherwise it returns a NULL value which is defined in stdio.h.
For example:
#include<stdio.h>
void main()
{
FILE *fp;
fp=fopen("cse.txt","r");
}
The above program will open a file "cse.txt" for reading. If no file exists with this name in the current directory, then the function will return NULL value, indicating no valid buffer is associated within the file.
Considering another example:
#include<stdio.h>
void main()
{
FILE *fp;
fp=fopen("cse.txt","w");
}
The above code will open a file named "cse.txt" for writing. If the file does not exists within the given path, then the function will create a new file and opens it to write. If the file already exists, then it will be opened in write mode but the previous contents will be deleted.
Every file has its own pointer variable. When we wish to read from a file or write to a file, we specify the file pointer variables as FILE *fp1, *fp2, *fp3;
The variables fp1,fp2, and fp3 are file pointers.
Example for a NULL pointer:
#include<stdio.h>
#include<conio.h> 
#include<stdlib.h>   //prototype for exit function
void main()
{
FILE *fp;
fp=fopen("cse.txt","w");
if(fp==NULL)
{
printf("cannot open the file");
exit(0);  //terminates the program.
}
 //here we can work on file(i.e. write to a file)..
}
If fopen() returns NULL, we can check whether the file is opened or not and accordingly print the message in to the file.
We can also combine the fopen() and if statements as follows:
if((fp=fopen("cse.txt","w"))==NULL)
printf("cannot open the file");
exit(0); //terminates the program.

Closing a File:

When all read, write, and other operations are done with an opened file, it must be closed immediately for the following reasons:
  • To reopen it in some other mode.
  • To prevent any misuse with the file.
  • To make the operations you have performed on the files successful.
To close a file, we must use the function named fclose().
The syntax of fclose() is as follows:
fclose(ptvar)
where ptvar is a pointer variable(fp).
The function fclose() closes the named stream. Pointer variable points to a file to be closed. All buffer associated with the stream are flushed before closing the file. On success, fclose() returns 0 otherwise, it returns end-of-function.
Example program:
A program code which demonstrates the functions fopen() and fclose().


#include<stdio.h>
#include<conio.h> 
#include<stdlib.h>   //prototype for exit function.
void main()
{
FILE *fp;
clrscr();
fp=fopen("cse.txt","w");
if(fp==NULL)
{
printf("cannot open the file");
exit(0); //terminates the program.
else
{
printf("File is opened successfully");
printf("\n Now you can work on your file in write mode");
}
if(fclose(fp)==0)
{
printf("\n File is closed now. cannot work on file");
}
getch();
}

Output for the above given program:
File is opened successfully
Now you can work on your file in write mode
File is closed now. cannot work on file

How the above program works?
In the above code, a file named "cse.txt" is opened. The if condition checks whether file is opened or not. If the file is not opened, it prints the message "cannot open the file" and terminates the program. If the file is opened, it prints the corresponding message. The condition fclose(fp)==0 checks whether the file pointed to by fp is closed successfully or not.
  •  Note: A file pointer is simply a variable like an integer or a character. It does not point to a file or the data in a file; it is simply used to indicate which file refers to the input/output operations.
From site : http://ctechrockz.blogspot.com/

Saturday, 20 April 2013

Introduction To File Handling.

  •  We normally often need to store data through our programs on some permanent storage devices so that we are able to access the data some other time. Such a data is stored on the memory device in the form of a data file. Thus,data files allow us to store information permanently, and to access and alter that information whenever necessary. The C library provides set of library functions to perform read and write operations on files. A computer file is a collection of data stored on a non volatile device in a computer system. Files exists on permanent storage devices, such as hard disks, DVDs, USB drives, and reels of magnetic tape. 
  • There are two different  types of data files, called stream oriented (or) standard data files and the system oriented (or) low level data files. 
  •  Stream oriented data files are generally easier to work with and are therefore more commonly used. These files are sub divided into two categories: The first category is of text files, that which consists of consecutive characters. These characters can be interpreted as strings or numbers or-else individual data items. The manner in which these characters  are interpreted will use library functions such as scanf and printf statements etc. The second is often referred to as unformulated data files. They organizes data into blocks containing contiguous bytes of information. These blocks represent more complex data structures, such as arrays and structures. A separate set of library functions are available for processing stream oriented data files of this type.
  •  System oriented data files are more closely related to the computer's operating system than stream oriented. They are somewhat more complicated to work with, though their use may be more efficient for certain kind of applications.
  •  Data files are most frequently used to store user's data. However data related to numbers can be efficiently stored in the form of binary files, which are also useful to handle file containing machine language contents. The files which are stored in binary format differ significantly from data(i.e.text files).
  • Text Files;which contain data that can be read in a text editor because the data has been encoded using a scheme such as ASCII or uni-code. Text files might include facts and figures used by business programs, such as a payroll file that contains employee numbers, names, and salaries.
  • Binary file;which contain data that has not been encoded as text. It mean that the binary file always contains binary digits. Examples include images and music.
         Although their contents vary, files have many common characteristics, as follows:
  • A byte is a small unit of storage; for example, in a simple text file, a byte holds only one character. Because a byte is so small. File sizes usually expressed in kilo bytes(thousands of bytes), mega bytes(millions of bytes), giga bytes(billions of bytes).
      The C language treats all the information that enters a program or leaves a program as a stream of bytes or series of bytes. We can work on files by using input or output streams.

For a quick summery, visit  the below given link.

http://ctechrockz.blogspot.in/2013/04/an-overview-of-files.html

From site : http://ctechrockz.blogspot.com/

An Overview Of Files.

What is a File?

  • A File is a collection of related records such as the records of employee in a company. Each record will be a collection of related data items called fields namely, employer name, number, department etc..Each field consists of group of characters. Many computer applications require that information must be written or read from an auxiliary device such as hard disk or floppy disk. Such a information  will be stored in the storage devices in the form of data files.
  • Data files allow us to store information permanently, and access or alter that information whenever required.

 How a File will be useful?

          There can be many reasons to use files.

    • The first and the foremost reason is need of permanency of storage of data. If we want to preserve the output of any program for future use, it is not possible with out files. All the inputting files have been printed with the help of any output statements like printf, putchar etc..are never available for future use and the only solution in that case is to write the output in files.Similarly, if there is a large amount of data generated as output by a program, storing that output in file will help in easy analysis of the output,as user can see the whole output at any time even after complete execution of the program. These situations will explain the need of output files. 
    • The input files are also equally important and useful. If a program needs a lot of data to be inputted, user cannot keep on typing that again again for repeated execution of the program. In that case, all input data can be once written in a file and then that file can be easily used as the input file. Moreover the transfer of input data and/or the output data from one computer to another can be easily done by using files.
           From site : http://ctechrockz.blogspot.com/