Friday, November 21, 2014

5.3 STANDARD C PREPROCESSOR


ü  Before a C program is complied it is passed through another program called “Preprocessor”.

ü  The C program is known as “Source Code”.

ü  The preprocessor works on the source code and creates ‘Expanded Source Code’. It is this expanded source code that is sent to the compiler for compilation.

 

Preprocessor Directives

 

1)      Macro expansion

(a)    Macros - #define

 

General Format:

      #define macro_name macro_expansion

e.g.    #define UPPER 25

§  This statement is called ‘macro expansion’.

§  During preprocessing, the preprocessor replaces every occurance of UPPER in the program with 25.

§  It is customary to use capital letters for macro templates as it makes it easy for programmers to pick out all the macro templates when reading through the program.

§  A macro definition is never to be terminated by a semicolon (;).

 

(b)   Macros with Arguments

Sample Code:

 

#include<stdio.h>

#define AREA(x) (3.14 * x * x)

void main()

{

      float r = 6.25, a;

      a = AREA(r );

      printf(“ Area of Circle = %f”, a);

}

 

OUTPUT

Area of Circle = 122.656250

 

§  Be careful not to leave a blank between the macro template and its argument while defining the macro.

§  The entire macro expansion should be enclosed within parentheses.

§  Macros can be split into multiple lines with a ‘\’ (back slash) present at the end of each line.

 

 

Macros vs. Functions

1.      In a macro call, the preprocessor replaces the macro template with its macro expansion in a literal way.

In a function call, the control is passed to a function along with certain arguments, some calculations are performed in the function and a useful value is returned back from the function.

2.      Macros make the program run faster but increase the program size, whereas functions make the program smaller and compact.

 

2)      File Inclusion

The preprocessor command for file inclusion looks like this:

            #include “filename”

OR      #include<filename>

and it simply cause the entire contents of filename to be inserted into the source code at that point in the program.

 

#include<goto.h>
This command would look for the file in the current directory as well as the specified list of directives as mentioned in the include search path that might have been set up.
#include ”goto.h”
This command would look for the file in the specified list of directories only.

 

When and why this feature is used?

§  It is a good programming practice, to keep different sections of a large program separate. These files are #included at the beginning of main program file.

§  There are some functions and some macro definitions that we need almost in all programs. The same can be stored in a file and that file can be included in every program we write.

 

3)      Conditional Compilation

(a)    #ifdef and #endif

§  If we want we can have the compiler skip over a part of the souces code by inserting the preprocessing commands #ifdef and #endif.

§  General Format:

 

#ifdef   macroname

       statement1;

       statement2;

       statement3;

#endif

 

(b)   #if and #elif

§  The #if directive can be used to test whether an expression evaluates to a nonzero value or not. If the result of the expression is nonzero, then sunsequent lines upto a #else, #elis or #endif are complied, otherwise they are skipped.

§  General Format:

 

void main()

{

      #if   TEST < = 5

                  statement1;

                  statement2;

                  statement3;

      #else

                  statement4;

                  statement5;

                  statement6;

      #endif

}

 

4)      Other Directives

(a)    #undef

In order to undefined a macro that has been earlier #defined, the directive

      #undef   macro  template

can be used.

ü  All subsequent macro definitions statements would evaluate to false.

 

(b)   #pragma

§  This directive can be used to turn on or turn of certain features.

(i)                 #pragma startup and #pragma exit

ü  These directives allow us to specify functions that are called upon program startup (before main() ) or program exit (just before the program teminates).

Example:

 

void fun1();

void fun2();

#prgma startup fun1

#pragma exit fun2

void main()

{

            printf(“\n Inside main”);

}

void fun1()

{

            printf(“\n Inside fun1”);

}

void fun2()

{

            printf(“\n Inside fun2”);

}

 

OUTPUT

Inside fun1

Inside main

Inside fun2

 

(ii)               #pragma warn

ü  The #prgama warn directive tells the compiler whether or not we want to suppress a specific warning.

Example:

 

            #pragma warn –rvl                  /* return value */

            #pragma warn –par                 /* parameter not used */

            #pragma warn +rch                 /* unreachable code */

§  The negative sign ( - ) would suppress the warnings.

§  The positive sign (+ ) would flash the warnings.

 

 

                                      

5.2 FILE MANAGEMENT

Many real-life problems involve large volumes of data and in such situations; the console oriented I/O operations (scanf, printf) pose two major problems:

(a)    It becomes cumbersome and time consuming to handle large volumes of data through terminals.

(b)   The entire data is lost when either the program is terminated or the computer is turned off.

 

It is necessary to have a more flexible approach where data can be stored on the disks and read whenever necessary, without destroying the data. This method employs the concept of files.

 

Def:

            A file is a place on the disk where a group of related data is stored. C supports a number of functions that have the ability to perform basic file operations, which include:

·         Naming a file

·         Opening a file

·         Reading data from a file

·         Writing data to a file

·         Closing a file

 

ü  Defining and opening a file

o   If we want to store data in a file we must specify certain things about the file to the operating system i.e. filename, data structure, purpose.

o   Filename is a string of characters that make up a valid filename. It may contain two parts, a primary name and an optional period with extension.

o   Data structure of a file is defined as FILE in the library of standard I/O function definitions.

o   When we open a file, we must specify what we want to do with the file i.e. what is the purpose of the file.

 

General Format:

            FILE  *fp;

            fp = fopen (“filename”, “mode”);

 

o   The first statement declares the variable fp as a “pointer to the data type FILE”.

o   The second statement opens the file named ‘filename’ and assigns an identifier to the FILE type pointer fp.

NOTE: This pointer (i.e. fp), contains all the information about the file is subsequently used as a communication link between the system and the program.

o   The second statement also specifies the purpose of opening this file. The mode does this job. Mode can be one of the following:

§  r : open the file for reading only

§  w : open the file for writing only

§  a : open the file for appending (or adding) data to it

 

ü  Closing a file

o   A file must be closed as soon as all operations on it have been completed. This ensures that all outstanding information associated with the file is flushed out from the buffers and all links to the file are broken.

o   Reasons for closing a file:

§  Prevents any accidental misuse of the file.

§  There is a limit to the number of files that can be kept open simultaneously.

§  Want to reopen the same file in a different mode.

 

General format:

            fclose(file_pointer);

This would close the file associated with the FILE pointer file_pointer.

 

Sample Code:

            …………       

FILE   *p1, *q2;

p1 = fopen(“INPUT”, “w”);

q2 = fopen(“OUTPUT”, “r”);

………….

………….

fclose (p1);

flcose (q2);

…………..

 

ü  Input/Output operations on file

(i)                 getc( ) and putc( ) Functions

Assume that a file is opened with mode w and file ponter fp1. Then, the statement,

            putc (v, fp1);

writes the character contained in the character variable v to the file associated with the FILE pointer fp1.

 

Similarly, getc( ) is used to read a chacater from a file that has been opened in read mode.

            v = getc(fp2);

 

NOTE: The getc( ) will return an end-of-file marker EOF, when end of the file has been reached.

 

NOTE: The end of the data is indicated by entering an EOF character, which is control-Z in the reference system.

 

 

 

(ii)               getw( ) and putw( ) Functions

The getw( ) and putw( ) are integer oriented functions and are thus sued to read and write integer values.

 

General form:

 

            putw( integer, fp);

            getw( fp);

 

(iii)             fprintf( ) and fscanf( ) Functions

The functions fprintf( ) and fscanf( ) perform I/O operations that are identical to the familiar printf( ) and scanf( ) functions, except that they work on files.

 

General form:

 

            fprintf( fp, “control string”, list);

 

where, fp is a file pointer associated with a file that has been opened for writing.

            control string contains output specifications for the items in the list.

            list may include variables, constants and strings.

 

e.g.      fprintf( f1, “%s%d%f”, name,age,7.5);

 

The general format of fscanf( ) is:

            fscanf( fp , “Control string”, list);

 

This statement would cause the reading of the items in the list from the file specified by fp, according to the specifications contained in the control string.

 

e.g.      fscanf( f2, “%s%d”, &item, &quantity);