CP unit-III
CP unit-III
1.#define
2.#endif
3. #ifdef
4.#line
5.#elif
6. #error
7. #ifndef
8. #pragma
9.#else
10.#if
1. #define
The #define directive defines an identifier and a character sequence (a
set of characters) that will be substituted for the identifier each time it
is encountered in the source file. The identifier is referred to as a
macro name and the replacement process as macro replacement. The
general form of the directive is
#define macro-name char-sequence
For example, if you wish to use the word LEFT for the value 1 and
the word RIGHT for the value 0, you could declare these two #define
directives:
#define LEFT 1
#define RIGHT 0
This causes the compiler to substitute a 1 or a 0 each time LEFT or
RIGHT is encountered in your source file. For example, the following
prints 0 1 2 on the screen:
printf("%d %d %d", RIGHT, LEFT, LEFT+1);
Defining Function-like Macros
The #define directive has another powerful feature: The macro name
can have arguments. Each time the macro name is encountered, the
arguments used in its definition are replaced by the actual
arguments found in the program. This form of a macro is called a
function-like macro. For example:
#include <stdio.h>
#define ABS(a) (a) < 0 ? -(a) : (a)
int main(void)
{
printf("abs of -1 and 1: %d %d", ABS(-1), ABS(1));
return 0;
}
2. #error
The #error directive forces the compiler to stop compilation. It is used
primarily for debugging. The general form of the #error directive is
3. #include
The #include directive tells the compiler to read another source file in
addition to the one that contains the #include directive. The name of
the source file must be enclosed between double quotes or angle
brackets. For example,
#include "stdio.h"
#include <stdio.h>
both cause the compiler to read and compile the header for the I/O
system library functions.
Include files can have #include directives in them.
6. #undef
7. #line
The #line directive changes the contents of _ _LINE_ _ and _ _FILE
_, which are predefined
identifiers in the compiler. The _ _LINE_ _ identifier contains the line
number of the currently compiled line of code. The _ _FILE_ _
identifier is a string that contains the name of the source file
being compiled. The general form for #line is
#line number "filename"
where number is any positive integer and becomes the new value of _
_LINE_ _, and the optional
filename is any valid file identifier, which becomes the new value of _
FILE_ _. #line is primarily
used for debugging and special applications.
#include <stdio.h>
#line 100 /* reset the line counter */
int main(void) /* line 100 */
{ /* line 101 */
printf("%d\n", _ _LINE_ _); /* line 102 */
return 0;
}
8. #pragma
#pragma is an implementation-defined directive that allows various
instructions to be given to the
Function Operation
int getchar(void);
int putchar(int c);
As its prototype shows, the getchar( ) function is declared as returning
an integer. However, you can assign this value to a char variable, as is
usually done, because the character is contained in the low-order byte.
(The high-order byte is usually zero.) getchar( ) returns EOF if an
error occurs. (The EOF macro is defined in <stdio.h> and is often
equal to –1.)
#include <stdio.h>
#include <ctype.h>
main()
{
char ch;
printf("Enter some text (type a period to quit).\n");
do
{
ch = getchar();
if(islower(ch))
ch = toupper(ch);
else
ch = tolower(ch);
putchar(ch);
} while (ch != '.');
Getch();
}
Explanation
The above program illustrates getchar( ) and putchar( ). It inputs
characters from the keyboard and displays them in reverse case. That
is, it prints uppercase as lowercase and lowercase as uppercase. To
stop the program, enter a period.
gets()::
The gets( ) function reads a string of characters entered at the
keyboard and stores them at the address pointed to by its argument.
You can type characters at the keyboard until you strike a carriage
return. The carriage return does not become part of the string; instead,
a null terminator is placed at the end, and gets( ) returns. In fact, you
cannot use gets( ) to return a carriage return (although getchar( ) can
puts()::
The puts( ) function writes its string argument to the screen
followed by a newline. Its prototype is
int puts(const char *str);
puts( ) recognizes the same backslash escape sequences as printf( ),
such as \t for tab. A call to puts ( ) requires far less overhead than the
same call to printf( ) because puts( ) can only output a string of
characters— it cannot output numbers or do format conversions.
Therefore, puts( ) takes up less space and runs faster than printf( ). For
this reason, the puts( ) function is often used when no format
conversions are required.
printf( )
The prototype for printf( ) is
int printf(const char *control_string, . . . );
The printf( ) function returns the number of characters written or a
negative value if an error occurs.
The control_string consists of two types of items. The first type is
composed of characters that will be printed on the screen. The second
type contains format specifiers that define the way the subsequent
arguments are displayed.
For example
printf("I like %c %s", 'C', "very much!");
displays
I like C very much!
Code Format
%a Hexadecimal output in the form 0xh.hhhhp+d (C99
only).
%A Hexadecimal output in the form 0Xh.hhhhP+d (C99
only).
%c Character.
%d Signed decimal integers.
%i Signed decimal integers.
%e Scientific notation (lowercase e).
%E Scientific notation (uppercase E).
%f Decimal floating point.
%g Uses %e or %f, whichever is shorter.
%G Uses %E or %F, whichever is shorter.
%o Unsigned octal.
%s String of characters.
%u Unsigned decimal integers.
%x Unsigned hexadecimal (lowercase letters).
%X Unsigned hexadecimal (uppercase letters).
%p Displays a pointer.
%n The associated argument must be a pointer to an integer. This
specifier causes the number of characters written (up to the point at
which the %n is encountered) to be stored in that integer.
%% Prints a % sign.
#include <stdio.h>
int main(void)
{
double f;
for(f=1.0; f<1.0e+10; f=f*10)
printf(''%g ", f);
return 0;
}
#include <stdio.h>
int main(void)
{
unsigned num;
for(num=0; num < 16; num++)
000
111
222
333
444
555
666
777
10 8 8
11 9 9
12 a A
13 b B
14 c C
15 d D
16 e E
17 f F
#include <stdio.h>
int main(void)
{
int count;
printf("this%n is a test\n", &count);
printf("%d", count);
return 0;
}
This program displays this is a test followed by the number 4. The %n
format specifier is used
primarily to enable your program to perform dynamic formatting.
8) The Minimum Field Width Specifier
An integer placed between the % sign and the format code acts as a
minimum field width specifier. For example, %05d will pad a number
of less than five digits with 0's so that its total length is five. The
following program demonstrates the minimum field width specifier:
#include <stdio.h>
int main (void)
{
double item;
item = 10.12304;
printf("%f\n", item);
printf(''%10f\n", item);
scanf( )
scanf( ) is the general -purpose console input routine. It can read all
the built-in data types and automatically convert numbers into the
proper internal format. It is much like the reverse of
printf( ). The prototype for scanf( ) is
Code Meaning
%a Reads a floating -point value (C99 only).
%c Reads a single character.
%d Reads a decimal integer.
%i Reads an integer in either decimal, octal, or hexadecimal
format.
%e Reads a floating -point number.
%f Reads a floating -point number.
%g Reads a floating -point number.
%o Reads an octal number.
%s Reads a string.
%x Reads a hexadecimal number.
%p Reads a pointer.
%n Receives an integer value equal to the number of
characters read so far.
%u Reads an unsigned decimal integer.
%[ ] Scans for a set of characters.
%% Reads a percent sign.
INTRODUCTION
Input means transferring data from input device to program. Output
means transferring data from program to output device. Here data
transfer is also called stream. Stream means a sequence of bits or
bytes.
By default, program I/O done through standard input and standard
output. Generally standard input device is keyboard and standard
output device is monitor(or screen). That is, by default program
connected to keyboard for input and program connected to monitor
for output.
File concept changes the standard input and standard output. That is,
program I/O done through the files. For program input, standard input
device keyboard is replaced with file and for program output standard
output device is replaced with the file. So, files allow a programmer
to do I/O with files.
Program that deals data with standard input and output devices is
temporary. That is, when the program ends , we loose data. So, to deal
with permanent data we use files.
Program that deals data with standard i/o devices is limited. That is,
not possible to transfer huge amount of data, that is possible only
through files.
Files
The file is a permanent storage medium in which we can store the
data permanently.
Or
A file represents a sequence of bytes on the disk where a group of
related data is stored. File is created for permanent storage of data.
Or
A File is a collection of data stored on a secondary storage device like
hard disk. File operation is to combine all the input data into a file and
then to operate through the C program. Various operations like
insertion, deletion, opening closing etc can be done upon a file. When
the program is terminated, the entire data is lost in C programming. If
you want to keep large volume of data, it is time consuming to enter
the entire data. But, if file is created these information can be accessed
using few commands.
Declaring a File
The data structure FILE, which is defined in stdio.h used to declare a
file.File control structure for streams.
typedef struct {
short level;
unsigned flags;
char fd;
unsigned char hold;
short bsize;
unsigned char *buffer, *curp;
unsigned istemp;
short token;
} FILE;
FILE *file_pointer;
Definition of File::
A file is a collection of related information. Actually files are residing
in secondary storage devices such as hard disk , floppy disk etc. (OR)
File is a set of record that can be accessed through the set of library
functions.
FILE *fp;
fp=fopen(const char *filename, const char *mode);
FILE *fp;
fp = fopen(“temp.txt”,”r”); (OR) fp = fopen(“temp.txt”,”w”);
Example:
The following code uses fopen( ) to open a file named TEST for
output.
#include <stdio.h>
main()
{
FILE *fp;
fp = fopen("test.txt", "w");
if(fp==NULL)
{
printf(''Cannot open file.\n");
exit(1);
}
-----------
-----------
-----------
-----------
fclose(fp);
getch()
}
2. Closing a File
int fcloseall(void);
fcloseall()
3. Writing a Character
The C I/O system defines two equivalent functions that output a
character: putc( ) and fputc( ). The putc( ) function writes characters
to a file that was previously opened for writing using the fopen( )
function. The prototype of this function is
int putc(int ch, FILE *fp);
fputc() finction returns a character c on success and returns EOF on
failure.
For example, consider the following statements:
char ch;
FILE *fwrite;
fwrite = fopen(“temp.txt”,”w”);
ch=’A’;
fputc(ch,fwrite);
Write one more character into the file “temp.txt” using the following
statements:
ch=’B’;
fputc(ch,fwrite);
#include<stdio.h>
int main()
{
char ch;
int i;
FILE *fwrite;
fwrite = fopen("temp.txt","w");
ch = 'A';
for(i=1;i<=26;i++)
{
fputc(ch,fwrite);
ch = ch + 1;
}
fclose(fwrite);
return 0;
}
After executing the above program “alpha.txt” looking like the
following:
4. Reading a Character
There are also two equivalent functions that input a character: getc( )
and fgetc( ). Both are defined
to preserve compatibility with older versions of C. The getc( )
function reads characters from a file opened in read mode by fopen( ).
The prototype of getc( ) is
int getc(FILE *fp);
where fp is a file pointer of type FILE returned by fopen( ).
For example, consider the following statements:
char ch;
FILE *fp;
Let us consider, the file “temp.txt” opened in read mode with the
contents specified in the below figure. Whenever the file opened , the
file pointer pointing to the first character in the file:
Now we read a character from the file using the following statement:
ch = fgetc(fp);
The above statement read a character ‘g’ from the file and
immediately forwards the file pointer to the next character and the
read character stored in variable ‘ch’. After reading a character from
the file with file pointer shown below:
The file pointer automatically moved the next character after reading
a character.
Read next character,
ch = fgetc(fp);
After reading a character from the file with file pointer shown below:
The following code displays all contents from the file “temp.txt”:
5. Using feof( )
C includes the function feof( ), which determines when the end of the
file has been encountered. The feof( ) function has this prototype:
int feof(FILE *fp);
feof( ) returns true if the end of the file has been reached; otherwise, it
returns zero. Therefore, the following routine reads a binary file until
the end of the file is encountered:
7. rewind( )
The rewind( ) function resets the file position indicator to the
beginning of the file specified as its
argument. That is, it "rewinds" the file. Its prototype is
void rewind(FILE *fp);
where fp is a valid file pointer.
The rewind() function repositions file pointer to the beginning of the
file. The following is the declaration of rewind() function:
rewind(fp);
After executing the above statement, the situation is looking like the
following:
int main()
{
FILE *fp;
fp = fopen("emp.dat", "w");
getc(fp);
if (ferror(fp) != 0)
{
printf("\nError reading from emp.dat");
}
}
9.Erasing Files
int main()
{
FILE *fp;
fp = fopen("emp.dat", "w");
getc(fp);
if (ferror(fp) != 0)
{
printf("\nError reading from emp.dat");
clearerr(fp);
}
}
This function stores the position of the file pointer associated with the
given stream in the location *pos.
The fsetpos() function sets the file pointer position. The following is
the declaration of fgetpos() function:
This function sets the file pointer associated with stream to a new
position.
fgetpos(fp,&pos);
printf(“\n File position = %ld”,pos);
After executing the above statements, displays File Position = 16
pos = pos – 8;
fsetpos(fp,&pos);
After executing the above statement, the situation is looking like the
following:
To read and write data types that are longer than 1 byte, the C file
system provides two functions:
fread( ) and fwrite( ). These functions allow the reading and writing of
blocks of any type of data.
Their prototypes are
size_t fread(void *buffer, size_t num_bytes, size_t count, FILE *fp);
Here,
I B.Tech COMPUTER PROGRAMMING UNIT-III 36
buffer Points to a block into which
data is read
num_bytes Length of each item read, in
bytes
count Number of items read
file_pointer Points to input stream
the following statement writes the contents of cust to the file pointed
to by fp:
fwrite(&cust, sizeof(struct struct_type), 1, fp);
You can perform random read and write operations using the ‘C’
language I/O system with the help of fseek( ), which sets the file
position indicator. Its prototype is shown here:
int fseek(FILE *fp, long int numbytes, int origin);
Here, fp is a file pointer returned by a call to fopen( ), numbytes is the
number of bytes from origin,
fseek(fp, -3 ,SEEK_END);
After executing the above statement, the situation is looking like the
following:
In the above statement ftell() returns the current file pointer for
stream. If the file is binary, the offset is measured in bytes from the
beginning of the file
FILE *fp;
fp = fopen(“TEST.TXT”,”w+”);
The following figure illustrates the situation after executing the above
statements and the file is successfully opened:
pos = ftell(fp);
printf(“\nPosition = %ld”,pos);
After executing the above statements, display Position = 0
fprinf(fp,”One Two”);
After executing the above statement, the contents “One Two” are
written to file “TEST.TXT”. The following figure illustrates this:
pos = ftell(fp);
printf(“\nPosition = %ld”,pos);
After executing the above statements, display Position = 7
fprinf(fp,” Three Four”);
After executing the above statement, the contents “One Two” are
written to file “TEST.TXT”. The following figure illustrates this:
pos = ftell(fp);
printf(“\nPosition = %ld”,pos);
After executing the above statements, display Position = 18
FILE *stud;
int rno,m1,m2,m3;
char name[20];
stud = fopen(“student.dat”,”r”);
fscanf(stud,”%d %s %d %d %d”,&rno,&name,&m1,&m2,&m3);
The above code reads student details from the file “student.dat” and
details are stored in the corresponding variables. The following figure
illustrates this:
The pointer stud pointing to the file “student.dat” and the file is
opened in read mode. The fscanf statement reads the contents from
If we use again the fscanf statement, then next student details are
stored in the corresponding variable as described above. The
following figure illustrates this:
Second fscanf statement reads the contents from the file and stores in
the corresponding variable. That is , 102 stored in rno, Rajesh stored
in name, 65 stored in m1, 45 stored in m2 and 71 stored in m3.
int main()
{
FILE *stud;
int rno,m1,m2,m3;
char name[20];
stud = fopen(“student.dat”,”r”);
while(fscanf(stud,”%d %s %d %d
%d”,&rno,&name,&m1,&m2,&m3))
{
printf(“\nRoll Number : %d”,rno);
printf(“\nName: %s”,name);
printf(“\nMarks – 1 : %d”,m1);
printf(“\nMarks – 2 : %d”,m2);
printf(“\nMarks – 3 : %d”,m3);
}
fclose(stud);
}
FILE *femp;
int eno;
char name[20];
float basic;
femp = fopen(“emp.dat”,”w”);
eno = 501;
strcpy(name,”Ganesh”);
basic = 9500.72;
fprintf(femp,”%d %s %f\n”,eno,name,basic);
The above code writes employee details into the file “emp.dat” and
details are stored into the file using variables eno, name and basic.
The following figure illustrates this:
The following code write one more employee details into “emp.dat”
FILE *femp;
int eno;
char name[20];
float basic;
femp = fopen(“emp.dat”,”w”);
eno = 501;
eno = 502;
strcpy(name,”Krishna”);
basic = 10750.56;
fprintf(femp,”%d %s %f\n”,eno,name,basic);
The above code illustrated with figure in the following way:
int main()
{
int n, eno, i;
char name[20];
float basic;
FILE *femp;
femp = fopen(“emp.dat”,”w”);
printf(“\nEnter number of employees:”);
scanf(“%d”,&n);
printf(“\nEnter %d employee details:\n”);
for(i=0;i<n;i++)
{
printf(“\nSerial number : %d”,i+1);
printf(“\nEmployee Number :”);