click on this link......

LinkGrand.com

Sunday, 31 March 2013

File in C



DISK I/O



Files :-
            Files are used for permanent data storage.  File is nothing but collection of data or information.  We need files because we know that when we will close the program all the contents O/S the variable will be lost.  & next time we will not get those values.
            In many situations such as maintaining data of students. Etc we need to store the data permaantly & files provide the way of storing data permanently.

            Files are stored on the dist (eg. Floppy, hard, etc) so file I/O is also known as disk I./O. is also known as disk I/o. have a file pointer which points to that file.  For creating a file pointer we use “FILE”.  The general format is,
            File name;
            Where File is the required key word,
·                     Indicates a pointer & ptrname is a name of file  pointer.  Which can be any valid identifier.
Ex.-     FILE * fp;
            FILE * Pl5*pr, *p3;

fopen ( ) –
            Before performing any operations ( such as read, write, modify, etc ) on the files we must open that file.  Without opening it we cannot perform any operations on file.
            For openening a file we use fopen ( ) the general format of fopen ( ) is,

Fileptr =
            fopen ( “filename” ,“mode”);
            Where filename is the file which we want to open.
            Mode means the type of such as read, write, append.
            The filename & mode must be in double quotes.
            Modes
            “r”                   read
            “w”                  write
            “a”                   append
           
            We are opening a file in read mode means we can only read the data from it.
            For opening the file in read mode first we must have that file already created.
            When we open the file is write mode every time a new file is created if the file already exists then compiler will overwrite it if not, a new file will be created.
            When we select the mode as append, the data can be added at the end of already created file.  If the file doesn’t exists. Like in write mode compiler also creates a new file in append mode
Ex-      fp: fopen (“rest”, “W”)
            Pt: fopen (“mydoc”, “r”)
            P1: fopen (“Infor.Txt”, “O”,)
·                     Single character I/O
1)            fputc ( ) :-
It is used for putting a character into the file at the position given by file ptr.  In other words we can write a single character into the file using fputc ( ).  The general form of fputc ( ) is as,

fputc ( Character, fileptr );

Where character is the character which we want to put in file.

And fileptr is the file pointer pointing to that particular position.
Ex. Char ch = *;
            fputc ( ch, fp );
      fputc ( ‘A’, p1 );
                        In the first example the value of ch i.e. * will be put at the position pointed by the file ptr fp.
                        In the second ex. Char ‘A’ will be put at the position pointed by P1.
·                     fgetc ( ) :-
It is used for getting a char from the file i.e. using fgetc ( ) we can input a single character at a time form the file.
            Syntax is,
fgetc ( fileptr );
Where fileptr is the file pointer which determines the position from where the character is to input.
            fgetc ( ) gives a character so to receive it we must have character exprenion.
Ex.
            fh = fgetc (fp);
            In the above ex. The char. From the file is read & will be stored in ch.
/*fputc demo*/
#include<stdio.h>
#include<conio.h>.
void main ( )

{
 FILE *fp; /*fileptr declaration */.
char ch;
cursor ( );
Ff=fopen (“test.txt”, “w”); /* opening file */.
if (fp=NULL)
}
printf (“\n Error in openng the file exit (0); * terminate the program */
}
printf (“\n Enter the character. 0 to stop )
while ( ‘) /*infinite loup */
{
ch = gevche ( );
fputc ( ch, fp ); /* writing to file */.
if ( ch = = 0)
Break;
} /End of while */.
Fclose (fp); /* closes the file */
}
/* fgetc demo*/
#include<stdio.h>
#include<conio.h>.
main ( )
{
file * fp;
char ch;
fp = fopen (“test.txt”, “r”);
if (fp == NULL)
{
printf ( “\n Error in opening files”);
exit (0);
}
printf (“)” The contents of file are \n );
While (1)
{
ch = fgetc (fp);
If (ch= = ‘0’)
break;
putch (on);
}
fclose (fp);
}

1.            Commandline arguments –
We know that we can pass the arguments to any user defined fun.  We have not assed any arguments to the main ( ).  But it is also possible to pass the arguments or parameters to main ( ).  These arguments can’t be passed in the C editor for passing arguments to main ( ) we have to run the program from Dos prompt or Command prompt or line.  As we are passing the arguments from command line, they are also known as command line arguments.
                       
                  There are two arguments of main ( ) one is integer & another is array of character ptrs. We can give any valid name to these arguments, but generally we have the name as argc & argv [ ] as,
                  Main ( int argc, char * argv [10] )
                  Where argc stores the total no. of arguments passed from command line. And argv stores the actual values of the arguments.
                  Running a program from command line means we have to run the exe file of that program.

/* command line arguments */
# include <stdio.h>
# include < conio.h>
void main ( int argc, char *argv [10%),
{
int i;
clescr ( );
printf (“\n total arguments = % d”, argc);
print (“|n The arguments are : \n”);
for (i=0, i<argc; i++)
                  printf ( “\n %s”, argv [i]);

}

                  In the above program first we have to make the exe, of it.  Suppose we have stored program as friend.c then the exe file will be friend. Exe.  We have to run this file from command prompt as,
                  Friend MANJITA SONALI SUJATA SAYALI

                  Then the argc will have the value 5 & argv will contain all these string.
                  Everything will be stored in the form of string though we have given no.

·         WAP to add to no’s the no’s are given from command line.
·         String I/O in file –
      Instead of having character by character input / output it is better to have string I/O. i.e. reading a whole string as well as writing a whole string at a time for this we can use fgets ( ) & fputs ( )

fputsc ( )-
      It is used for putting or writing the whole string in to the file.  The syntax is
      Fputs ( string, fileptr );
     
Where the string is which we want to put or write in the file.
String should specify the address of the containts which we want to put in file.
      And fileptr is the file pointer pointing to that file.
Ex.
      Char name [20] = “YASH CHOPRA”
fputs (name.fe);
                 

                  The above statements writes the name YASH CHOPRA at the location pointed by fp. Nere name specifies the starting address of array name.

fgets ( ) –
                  It is used for reading a string from the file. Here also like fputs we have to provide a string variable & file pointer with this we have to provide the no. of characters we want to read from the file.  The syntax is,
fgets ( String, n, fileptr );
                  Where a string is which we want to get.




                  & n is no. of characters we want to read from the file.
Ex.
                  fgets ( name, 10, fp )
                  The above statement will read 10 characters from the file & will store them in name.

·         WAP
1)      Writing a name in the file.
2)      Reading the same name from that file.
                 
·         fprintf ( ) & fspnf ( ) –
      Like the formatted I/O fun } printf ( ) & scanf ( ) we can also have formatted I/O fun’s for file as fscanf ( ) & fprintf ( ).
fscanf ( ) –
      It is used for reading or input the values from file.
      It is similar to scanf ( ) statement here the input values will be taken from the file.  The syntax is,
      fscanf ( fileptr, control string, list of arg );
      Where fileptr is the file pointer which points to the file from which we want to input the values.
      Control string is the string having format specifiers.
      List of arguments is the different arguments in which use we want to store the values.
Ex.
      Int rno; char name [20];
      fscanf (fp, “%d%s”, & rno, name );

·         fprintf ( )
      If is used for writing or putting the data into the file the syntax is,
      fprintf ( fileptr, control string, list of arg );
Ex.
      Int rno = 20;
      Char name [20] = “JAGRUTI”;
      fprintf (fp, “%d%S”, rno, name );
     
      The above statement writs the value 20 & JAGRUTI in the file pointed by fp.
/*PROGRAME FOR fprint ( ) demo */
#include <stdio.h>
#include<conio.h>
void main ( )
{
ink rno;
char name [20];
FILE * fp; /* file ptr decl^ */
Clrsor ( );
fp = fopen (“testr.txt”, “w”); /*opening file in write mod /.

if (fp = = NULL )
      {printf ( “\n Error in opening the file”);
      exit (0); /* terminates the program */
}

printf (“\n Enter roll no & name : ‘);
scanf (“%d%s”, & rno, name);
fprintf (fp, “%d%s”, rno. Name );
/*writing to file */
fclose (fp); closes the file */
}

/*PROGRAM FOR fscanf ( ) demo ^/
# include <stdio.h>
#I include <conio.h>
void main ( )
{
int rno;
char name [20];
FILE *fp;
Clrscr ( );
fp = fopen ( “test2.txt”, “?”);
if (fp = = NULL)
{printf (“\n Error in opening the file”);
exit (0);
}
fscanf (fp, “%d%s”, &r no, name);
printf (“\n Roll no : % d \n Name: % s” , rno, name);
fclose (fp);
}

fwrite ( ) –
      It is used for writing a fixed block of data into the file.  It is mainly used when we want to write the data from structures into file.  The general format of furite( ) is,
      Where address specifies the location from where the data stored.

      Which we want to write in file.
      Size specifies the size of every block.
      N specifies the no. of blocks of the size.
      Fileptr is the file pointer pointing to that file where we want to write the data.
Ex 1) struct student S;
      Fwrite ( &s, size of (struct student, 1, fp);
     
3)      int a[10];
fwrite (a, size of (int), 10, fp1);

                  The first example writes one block of size equal to the size of student structures at the location & s in the file pointed by fp.
                  The second example writes ten blocks of size equal to the size of into at the location a in the file pointed by fp1.

fread ( )-
                  fread ( ) is used for reading the fixed block of data from the file.  If we want to use fread ( ) for reading the data from file, the file shold be created by using fwrite ( ) otherwise we may get unwanted results.
                  The syntax is, similar to furite ( ) as,
                  fread ( address, size, n, fileptr );
Ex.
                  struct student s;
                  fread ( & s, size of (struct student), 1, fp );

                  The above statements reads one block of size equal to size of structure student from the file pointed by fp & stores the data at the location pointed by &s.

Decision making in C



Decision making in C

We have seen that a C program is group of statement which are normally executed
sequentially in order to appear .This happens when no options or no representation of certain calculations are necessary, but in practice we have number of  statements based on certain conditions or we have to repeat a group of statements until certain  specified conditions are made .This involves a kind of decision making to see whether a particular condition has occurred or not & these conditions direct  the computer to execute certain statement.
The C language has the decision making capability and following statement  supports decision making capability.
1 if statement
2 switch statement
3 conditional statement
4 go to statement

1 if statement

If statement is a powerful  decision making statement and is used to control the flow of execution of statements.

It is a  decision making statement & it has the following form

if( test expression / condition )

It allows the computer to evaluate the expression first and then depending on whether the
Value of expression is true or false , it transfers the control to a particular statement .
At this point it has two parts i.e. for true & for false.


          

Depending on the complexity of program the if statement are of following type

i. Simple if statement
the general form is

            if (test condition )
            {
                        statement block ;
            }
next statement;
statement block may have one or more than one statements .
if the test condition is true then statement block will be executed ; otherwise it is skipped & next statement is evaluated.
Eg.


main( )
{
            int a;
            printf ( "Enter value for a ");
            scant ( "%d", &a );
            if(a>100)
            {
                        printf ( "a is greater than 100" ) ;
            }
printf ( "HAVE  A GOOD DAY" ) ;
}

The if ….else statement
The if …else statement is an extention of the simple  if statement .
The general form of if - else  statement   is

if (test condition /expression)
{
            true block statement (s);
}
else
{
            false block statement (s);
}
next statement;

if the test expression is true then the true block statement s ,immediately following the if statement are executed ; otherwise the false block statement s are executed .
In either case ,either true block or false block will be executed ,not both .
In both the case ,the control is transferred subsequently to statement –x as shown below.




main( )
{
            int i;
            printf ( "Enter value of i ");
            scant ( "%d", &i ) ;
            if(i=5)
            {
                        printf ( "You entered 5" ) ;
            }
            else
            {
                        printf ( "You entered something other than 5" ) ;
            }
}

And here is the output of two runs of this program...

Enter value of i 200
You entered 5
Enter value of i 9999
You entered 5


Example :- In a company an employee is paid as under:
            If his basic salary is less than Rs. 1500, then HRA = 10% of basic
            salary and DA = 90% of basic. If his salary is either equal to or above
            Rs. 1500, then HRA = Rs. 500 and DA = 98% of basic salary. If the
            employee's salary is input through the keyboard write a program to
            find his gross salary.
main( )
{
            float bs, gs, da, hra;
            printf ( "Enter basic salary " ) ;
            scant ("%f",&bs);
            if (bs< 1500)
            {
                        hra=bs*10/100;
                        da=bs*90/100;
            }
            else
            {
                        hra = 500:
                        da=bs*98/100;
}
gs = bs+hra+da;
printf ( "gross salary = Rs. %f, gs);
}

Nesting of if..else statement
When a series of decisions are involved , we may have to use more than one if..else
Statement  in nested form as follows

The logic of execution is shown in the flowchart below
If the condition 1 is false , the statement 3 will be executed ; otherwise it continues to perform the second test .If the condition 2 is true ,the statement 1 will be evaluated ;
Otherwise the statement  2 will be evaluated & then the control is transferred to the statement x .

  if ( test condition )
{         
            if ( test condition )
            {
                        statement 1;
            }
            else
            {
                        statement 2;
            }
}
else
{
            statement 3 ;
}
statement x;


main()
{
            int ml , m2 , m3 , m4 , m5;
            printf ( "Enter marks in five subjects ") ;
            scant ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5 ) ;

            per = ( ml + m2 + m3 + m4 + m5 ) /5;

            if ( per >= 60 )
                        printf ( "First division ") ;
                        else
                        {
                        if ( per >= 50 )
                                    printf ( "Second division" ) ;
                                    else
                                    {
                                    if(per>=40)
                                                printf ( "Third division" ) ;
                                                else
                                                            printf ( "Fail" ) ;
}

Observe that the program uses nested if-elses. This leads to thre<
disadvantages:
(a)    As the number of conditions go on increasing the level o
indentation also goes on increasing. As a result the whol(
program creeps to the right.
(b)    Care needs to be exercised to match the corresponding ifs an(
ciscs.
(c)    Care needs to be exercised to match the corresponding pair o
braces.
The else if ladder
There is another way of putting ifs together when multipath  decision are involved .
A multipath decision is a chain of ifs in which the statement associated with each else is an it.
The general form is ;

if ( condition  1)
            statement 1;
else if ( condition )
                        statement  2;
                        else if (condition )
                                    statement 3;
                                    …………
                                    …………
                                    else if (condition n)
                                                statement –n ;
                                                else
                                                        default statement ;
            statement x ;

This construct is known as else if ladder .
The condition are evaluated from the top of the ladder , downwards  .As soon as atrue condition is found ,the statement associated with it is executed & control is transferred  to the statement x, skipping the rest of the ladder when all the n conditions become false , then the final else containing the default statement will be executed .
The flowchart shows the logic of execution of else it ladder statements.






Switch

It is also one kind of multi-way decision making structure .
So it is an option to nested if .
It is very easy to understand as compared to nested if  because when the conditions in the nested if statement increases its complexity also increases i.e. the structure becomes more & more complicated .
But with these advantages switch structure also have some limitations
In switch we can only test for fixed values of an expression .
But when we want to text the condition such as >= ,<=  etc .
There is no alternative to nested if in such situations you have to use nested if only the general form of switch is as follows:

switch(expression)
{         
             case value1:
                                    block of statements ;

case value2:
                                    block of statements ;

case value3:
                                    block of statements ;
                        .
                        .
                   .

case value n:
                                    block of statements ;

default :
                                    block of statements ;

}


In the above structure switch is a necessary keyword .
Expression can be any expression or a variable.
Case is the necessary keyword
value 1 will represent some fixed value of expression .
If the expression result in value 1  then , the block of statements in first case will be executed .
You  must provide colon ( :) after each case value .
Similarly value 2 ,value 3 …….value n are different possible values of the expression .
If no case value is matched ,
The expression the default part will be executed .
The default part is optional in switch .
One more advantage of is that in switch structure if we want to execute multiple statements after one case , there is no need of using curly brackets.

switch

#include<stdio.h>
main( )
I
char ch;
clrscr();
printf (" please enter your choice) ;
ch = touppcr(ch):
switch (ch)
{
case 'R':
            printf ("RED") ;
            break :
case 'w':
            printf (" white" ) ;
            break ;
case 'v':
            print (" violet ") ;
}
getch( );

}
The goto Statement

Avoid goto statements! They make a C programmer's life miserable.
There is seldom a legitimate reason for using goto, and its use is one
of the reasons that programs become unreliable, unreadable, and hard
to debug. And yet many programmers (especially those using
BASIC) find goto .
In a difficult programming situation it seems so easy to use a goto to
take the control where you want to. However, almost always, there
is a more elegant way of writing the same program using if, for, while
and switch. These constructs are far more logical and easy to under-
stand.
A goto statement can cause program control to end up almost
anywhere in the program, for reasons that are often hard to unravel.
Trust me, with good programming skills, goto can always be avoided.
This is the First and last time that we are going to use goto in this
book.
•For sake of completeness of the book, here is how the goto is used.
Consider the following program.

main( )
{
int goals;
printf ( "Enter the number of goals scored against India' ) ;
scant ( "%d", goats ) ;
           
if(goals<=5)
            goto sos :
           
      else
      {
                        printf ( 'About time soccer players learnt C\n" ) ;
                        printf ( 'and said goodbye! adieu! to soccer" ) ;
            exit( ) ; /* terminates program execution */
      };

sos:
            printf ( "To err is human!' ) ;
}
And here are two sample runs of the program...
Enter the number of goals scored against India 3
To err is human!
Enter the number of goals scored against India 7
About time soccer players learnt C
and said goodbye! adieu! to soccer