Unit Iii: 1 A. Define Preprocessor Directive? Explain The Pre-Processor Directives in Detail
Unit Iii: 1 A. Define Preprocessor Directive? Explain The Pre-Processor Directives in Detail
Unit Iii: 1 A. Define Preprocessor Directive? Explain The Pre-Processor Directives in Detail
Macros:
Macros are piece of code in a program which is given some name. Whenever this name is
encountered by the compiler the compiler replaces the name with the actual piece of code.
Simple Macros:
• The ‘#define’ directive is used to define a macro. #include <stdio.h>
// macro definition #define LIMIT 5 int main()
{
int i;
for(i = 0; i < LIMIT; i++) {
printf(“%d”,i);
}
return 0; }
Macros with arguments: We can also pass arguments to macros. Macros defined
with arguments works similarly as functions.
#include <stdio.h>
// macro with parameter #define AREA(l, b) (l * b) int main()
{
int l1 = 10, l2 = 5, area;
area = AREA(l1, l2);
printf("Area of rectangle is: “,area);
return 0;
}
Macros with nested arguments:
#include <stdio.h>
// macro with parameter
#define M 5 #define N M+2 int main()
{
printf(“%d”,N);
return 0;
}
File Inclusion:
This type of preprocessor directive tells the compiler to include a file in the source code
program. There are two types of files which can be included by the user in the program.
• Header File or Standard files: These files contains definition of pre-defined functions like
sqrt(), strlen() etc.
• These files must be included for working with these functions.
• Different function are declared in different header files.
• For example standard I/O functions are in ‘stdio’ file whereas functions which perform
string operations are in ‘string’ file.
Syntax:
#include<file_name >
Ex: #include<string.h>
where file_name is the name of file to be included. The ‘<‘ and ‘>’ brackets tells the compiler to
look for the file in standard directory.
• user defined files: When a program becomes very large, it is good practice to divide it into
smaller files and include whenever needed. These types of files are user defined files. These files
can be included as: #include "filename"
Conditional Compilation:
Conditional Compilation directives are type of directives which helps to compile a specific
portion of the program or to skip compilation of some specific part of the program based on some
conditions.
• In C, a programmer can instruct the preprocessor whether or not to include certain section
of the code. This is accomplished using conditional directives.
• These are similar to if statements in syntax and usage. However, unlike if statements
which are executed during runtime, the conditional directives are executed before compilation by
the preprocessor.
• These directives are used whenever there is a need to compile a portion of the program
conditionally. It is also known as conditional compilation.
• The most common conditional directive #ifdef (spelt as if-defined) verifies if a given
identifier is defined or not.
• The syntax for its usage is :#ifdef identifier or #if defined (identifier).
• The source code following #ifdef will be compiled only if the given identifier is defined
either in the code or if it is provided as a compilation option as - identifier_name .
• The opposite of #ifdef is #ifndef, which is written as #ifndef identifier or #if !defined
(identifier).
• Consider the following example:
#if defined (MAX)
#define MIN 20
#else
#define MAX 100
#define MIN 200
#endif
• Here, MIN 20 will be defined only if the constant MAX is defined earlier than MIN
20. Else, both MAX and MIN will be defined with values 100 and 200 respectively.
#include <stdio.h>
#if defined (MAX)
#define MIN 20
#else
#endif
#define MAX 100
#define MIN 200
void main() {
printf("MAX value = %d, MIN value = %d\n", MAX, MIN);
}
Similar to if-else-if construct, we have a #if-#elif which is used in creating a chain of #if-else
statements that can be used to conditionally compile a portion of code.
The general syntax for #if, #elif, #else, #endif is given below:
#if expression1
statement_block1; #elif expression2
statement_block2;
#elif expression3
statement_block3;
#else
#endif
statement_block4;
#include <stdio.h>
#if BACKGROUND == 7
#define FOREGROUND 0
#elif BACKGROUND == 6
#define FOREGROUND 1
#else
#endif
#define FOREGROUND 6
void main() {
printf("FOREGROUND value = %d\n", FOREGROUND);
}
Program to find minimum of two numbers using macros
#include<stdio.h>
#define MIN(a,b) a>b?a:b
void main()
{
printf("Minimum is %d",MIN(34,4));
}
Other directives:
• The #undef directive “undefines” a symbolic constant or a macro identifier that has been
defined earlier; i.e., it negates the effects of a #define directive that may have appeared earlier in
the program.
• The #undef directive is used to remove values defined by #define directives so that they
can be redefined with new values.
• The format of #undef is #undef symbolic_name
• Given below is an example for #undef: #include <stdio.h>
#define TEMP 20
int main() {
printf("%d\n", TEMP);
#ifdef TEMP
#undef TEMP #define TEMP 99
Here, the code first prints 20 and then prints99.
#else
#endif
#define TEMP 999
printf("%d\n", TEMP); return 0;
}
1 b. Write a C program to merge the contents given two existing files into new file.
#include <stdio.h>
#include <stdlib.h>
void main()
{
// Open two files to be merged
FILE *fp1 = fopen("w.c", "r");
FILE *fp2 = fopen("ww.c", "r");
// Open file to store the result
}
// Copy contents of first file to file3.txt
while ((c = fgetc(fp1)) != EOF)
fputc(c, fp3);
// Copy contents of second file to file3.txt
while ((c = fgetc(fp2)) != EOF)
fputc(c, fp3);
printf("Merged w.c and ww.c into r.c");
fclose(fp1);
fclose(fp2);
fclose(fp3);
}
2 a. Write a C program which copies one file to another, replacing all lowercase characters
with their uppercase equivalents.
#include <stdio.h>
#include<stdlib.h>
void main()
{
FILE *fp,*ft;
char ch;
fp=fopen("w.c","r");
ft=fopen("ww.c","w");
if(fp==NULL|| ft==NULL)
{
puts("Cannot open file");
exit(0);
}
while((ch=fgetc(fp))!=EOF)
{if(ch>=97&&ch<=122)
ch=ch-32;
fputc(ch,ft);
}
fclose(fp);
fclose(ft);
File Operations
In C, you can perform four major operations on the file, either text or binary:
When working with files, you need to declare a pointer of type file. This declaration is needed for
communication between the file and program.
Functions fread() and fwrite() are used for reading from and writing to a file on the disk
respectively in case of binary files.
Writing to a binary file
To write into a binary file, you need to use the function fwrite(). The functions takes four
arguments: Address of data to be written in disk, Size of data to be written in disk, number of such
type of data and pointer to the file where you want to write.
fwrite(address_data,size_data,numbers_data,pointer_to_file);
Example:
#include <stdio.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
if ((fptr = fopen("C:\\program.bin","wb")) == NULL)
{
printf("Error! opening file"); // Program exits if the file pointer returns NULL.
exit(1);
}
for(n = 1; n < 5; ++n)
{
num.n1 = n;
num.n2 = 5n;
num.n3 = 5n + 1;
fwrite(&num, sizeof(struct threeNum), 1, fptr);
}
fclose(fptr);
return 0;
}
Example:
#include <stdio.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
3 a. Write a C program to count the number of times a character occurs in a text file. The
file name and the character are supplied as command line arguments
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
if( argc!=4 )
{
printf( "pass correct way of command line arguments like inputfile outputfile character want
to search\n");
exit(0);
}
finp=fopen(argv[1], "r");
if( finp==NULL)
{
perror( "fopen for the input file failed" );
exit(0);
}
output=fopen(argv[2], "w");
if(output==NULL )
{
perror( "fopen for the output file failed" );
fclose( finp );
exit(0);
}
}
fprintf(output,"The search character is '%c' and it occurred %d times\n", argv[3][0], ex);
fclose(finp);
fclose(output);
return 0;
}
1. fseek()
2. ftell()
3. rewind()
We use the fseek() function to move the file position to a desired location.
Syntax:
fseek(fptr,offset,position);
Where, fptr is the file pointer. offset which is of type long, specifies the number of positions (in
bytes) to move in the file from the location specified by the position.
The position can take the following values.
Following are the list of operations we can perform using the fseek() function.
Operation Description
fseek(fptr, N, 1) This will take us N bytes forward from the current position in the
file.
fseek(fptr, -N, 1) This will take us N bytes backward from the current position in the
file.
fseek(fptr, -N, 2) This will take us N bytes backward from the end position in the file.
Example:
#include <stdio.h>
int main ()
{
FILE *fp;
fp = fopen("file.txt","w+");
fputs("This is KMIT", fp);
fseek( fp, 7, SEEK_SET );
fputs(" C Programming Language", fp);
fclose(fp);
return(0);
}
The ftell() function tells us about the current position in the file (in bytes).
Syntax:
pos=ftell(fptr);
Where, fptr is a file pointer. pos holds the current position i.e., total bytes read (or written).
Example:
If a file has 10 bytes of data and if the ftell() function returns 4 then, it means that 4 bytes has
already been read (or written).
#include<stdio.h>
int main()
{
FILE *fp = fopen("test.txt","r");
char string[20];
fscanf(fp,"%s",string);
printf("%ld", ftell(fp));
return 0;
}
We use the rewind() function to return back to the starting point in the file.
Syntax:
rewind(fptr);
Where, fptr is a file pointer.
Example
#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
char c;
clrscr();
fp=fopen("file.txt","r");
while((c=fgetc(fp))!=EOF)
{
printf("%c",c);
}
rewind(fp);//moves the file pointer at beginning of the file
while((c=fgetc(fp))!=EOF)
{
printf("%c",c);
}
fclose(fp);
getch();
}
The contents in file.txt is “ this is a simple text”
The output can be displayed as “this is a simple textthis is a simple text”.
4 a. List and explain various file read/write functions available in C with examples
File handling in C enables us to create, update, read, and delete the files stored on the local file
system through our C program. The following operations can be performed on a file.
There are many functions in the C library to open, read, write, search and close the file. A list of
file functions are given below:
*fpointer is the pointer to the file that establishes a connection between the file and the program.
The simplest functions used while performing operations on reading and writing characters in a
file are getc() and putc() respectively.
In order to read and write a set of data in a file, we use the fscanf() and fprintf() operators.
Mode Description
#include <stdio.h>
#include <stdlib.h>
int main()
printf("Welcome to PPS!\n\n");
char character;
FILE *fpointer;
if(fpointer == NULL)
exit(0);
fclose(fpointer);
return 0;}
#include <stdio.h>
int main(){
FILE * file;
char str[500];
if (file = fopen("hello.txt", "r")){
while(fscanf(file,"%s", str)!=EOF){
printf("%s", str);
}
}
else
printf("Error!”);
fclose(file);
return 0;
}
Output
LearnprogrammingattutorialsPoint
fgets()
The fget() function in C is used to read string from the stream.
Syntax
char* fgets(char *string, int length, FILE *stream)
Parameter
char *string: It is a string which will store the data from the string.
int length: It is an int which gives the length of string to be considered.
FILE *stream: It is the pointer to the opened file.
Example
#include <stdio.h>
int main(){
FILE * file;
char str[500];
if (file = fopen("hello.txt", "r")){
printf("%s", fgets(str, 50, file));
}
fclose(file);
return 0;
}
Output
Learn programming at tutorials Point
fgetc()
The fgetc() function in C is used to return a single character from the file. It gets a character from
the file and returns EOF at the end of file.
Syntax
char* fgetc(FILE *stream)
Parameter
FILE *stream: It is the pointer to the opened file.
Example
#include <stdio.h>
int main(){
FILE * file;
char str;
if (file = fopen("hello.txt", "r")){
while((str=fgetc(file))!=EOF)
printf("%c",str);
}
fclose(file);
return 0;
}
Output
Learn programming at tutorials Point
Writing Data to a file in C
We can write data to a file in C using the fprintf(), fputs(), fputc() functions. All are used to write
contents to a file.
Let’s see the working of each of the function −
fprintf()
The fprintf() function is used to write data to a file. It writes a set of characters in a file.
Syntax
int fprintf(FILE *stream, char *string[])
Parameters
FILE for *stream: It is the pointer to the opened file.
char *string[]: It is the character array that we want to write in the file.
Example
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("hello.txt", "w")){
if(fprintf(file, "tutorials Point”) >= 0)
printf("Write operation successful");
}
fclose(file);
return 0;
}
Output
Write operation successful
fputs()
The fputs() function in C can be used to write to a file. It is used to write a line (character line) to
the file.
Syntax
int fputs(const char *string, FILE *stream)
Parameters
Constant char *string[]: It is the character array that we want to write in the file.
FILE for *stream: It is the pointer to the opened file.
Example
int main(){
FILE * file;
if (file = fopen("hello.txt", "w")){
if(fputs("KMIT", file) >= 0)
printf("String written to the file successfully...");
}
fclose(file);
return 0;
}
Output
String written to the file successfully…
fputc()
The fputc() function is used to write a single character to the file.
Syntax
int fputc(char character , FILE *stream)
Parameters
char character : It is the character that we want to write in the file.
FILE for *stream: It is the pointer to the opened file.
Example
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("hello.txt", "w")){
fputc('T', file);
}
fclose(file);
return 0;
}
Output
‘T’ is written to the file.
fclose()
The fclose() function is used to close the open file. We should close the file after performing
operations on it to save the operations that we have applied to it.
Syntax
fclose(FILE *stream)
Parameters
FILE for *stream: It is the pointer to the opened file.
Example
#include <stdio.h>
int main(){
FILE * file;
char string[300];
if (file = fopen("hello.txt", "a+")){
while(fscanf(file,"%s", string)!=EOF){
printf("%s", string);
}
fputs("Hello", file);
}
fclose(file);
return 0;
}
Output
Learnprogramming
Text files are the normal .txt files. You can easily create text files using any simple text editors
such as Notepad.
When you open those files, you'll see all the contents within the file as plain text. You can easily
edit or delete the contents.
They take minimum effort to maintain, are easily readable, and provide the least security and takes
bigger storage space.Reading and writing to a text file
For reading and writing to a text file, we use the functions fprintf() and fscanf().
#include <stdio.h>
int main()
{
int num;
FILE *fptr;
if ((fptr = fopen("C:\\program.txt","r")) == NULL){
printf("Error! opening file"); // Program exits if the file pointer returns NULL.
exit(1);
}
fscanf(fptr,"%d", &num);
printf("Value of n=%d", num);
fclose(fptr);
return 0;
}
1. Text files
2. Binary files
1. Text files
Text files are the normal .txt files. You can easily create text files using any simple text editors
such as Notepad.
When you open those files, you'll see all the contents within the file as plain text. You can easily
edit or delete the contents.
They take minimum effort to maintain, are easily readable, and provide the least security and takes
bigger storage space.
2. Binary files
Binary files are mostly the .bin files in your computer.
Instead of storing data in plain text, they store it in the binary form (0's and 1's).
They can hold a higher amount of data, are not readable easily, and provides better security than
text files.
Like many other languages 'C' provides following file management functions,
Creation of a file
Opening a file
Reading a file
Writing to a file
Closing a file
Following are the most important file management functions available in 'C,'
function purpose
where,
fp – file pointer
# include <stdio.h>
int main( )
{
FILE *fp ;
char c ;
printf( "Opening the file test.c in read mode" ) ;
fp = fopen ( "test.c", "r" ) ; // opening an existing file
if ( fp == NULL )
{
printf ( "Could not open file test.c" ) ;
return 1;
}
printf( "Reading the file test.c" ) ;
while ( 1 )
{
c = fgetc ( fp ) ; // reading the file
if( feof(fp) )
break ;
printf ( "%c", c ) ;
}
printf("Closing the file test.c as end of file is reached.");
fclose ( fp ) ; // Closing the file
return 0;
}
The function ferror() is used for checking the errors in the stream.
Syntax:
int ferror(FILE *stream);
This function returns 0 if there are no errors and a value if there are some errors.
Following are the functions which are used for detecting the errors:
6 b. Write a C program to copy the data from one file to another file.
#include <stdio.h>
#include<stdlib.h>
void main()
{
FILE *fp,*ft;
char ch;
fp=fopen("file1.txt","r");
ft=fopen("file2.txt","w");
if(fp==NULL)
{
puts("Cannot open file");
exit(0);
}
if(ft==NULL)
{
puts("Cannot open file");
}
while((ch=fgetc(fp))!=EOF)
{
fputc(ch,ft);
}
fclose(fp);
fclose(ft);
fp=fopen("file2.txt","r");
while((ch=fgetc(fp))!=EOF)
{
putchar(ch);
}
fclose(fp);
}
7 a. Write a C program read and write the content of the file using fprintf( ) and fscanf( )
functions.
#include<stdio.h>
#include<conio.h>
struct emp
{
char name[10];
int age;
};
main()
{
struct emp e;
FILE *p,*q;
p = fopen(“one.txt”, “a”);
q = fopen(“one.txt”, “r”);
printf(“Enter Name and Age”);
scanf(“%s %d”, e.name, &e.age);
fprintf(p,“%s %d”, e.name, e.age);
fclose(p);
do
{
fscanf(q,”%s %d”, e.name, e.age);
printf(“%s %d”, e.name, e.age);
}
while(!eof(q));
}
In case of success, fread/fwrite return the number of bytes actually read/written from/to the stream
opened by fopen function. In case of failure, a lesser number of byes (then requested to read/write)
is returned.
fscanf()
Declaration: int fscanf(FILE *fp, const char *format, …)
fscanf() function is used to read formatted data from a file. In a C program, we use fscanf() as
below.
8. a. Write a program to store students information (names, marks) into a file and print the
information from the file.
#include<stdio.h>
int main() {
char name[50];
int marks,i,n;
return;
}
for (i=0;i<n;++i) {
printf("For student%d\nEnter name: ",i+1);
scanf("%s",name);
if(fptr==NULL) {
printf("Error!");
return;
}
for (i=0;i<n;++i) {
fscanf(fptr,"\nName: %s \nMarks=%d \n",name,&marks);
}
fclose(fptr);
return 0;
A text file stores data in the form of alphabets, digits and other special symbols by storing
their ASCII values and are in a human readable format. For example, any file with a .txt,
.c, etc extension. Whereas, a binary file contains a sequence or a collection of bytes which
are not in a human readable format. For example, files with .exe, .mp3, etc extension. It
represents custom data.
A small error in a textual file can be recognized and eliminated when seen. Whereas, a
small error in a binary file corrupts the file and is not easy to detect.
Since the data is not human readable it also adds to the security of the content as one might
not be able to get data if the structure is not known.
9 a. Write a ‘C’ program to count the number of characters, words, lines in a file.
#include <stdio.h>
#define MAX_LEN 1024
int main() {
char ch;
fp = fopen(file_name, "r");
if(fp == NULL) {
printf("Could not open the file %s\n", file_name);
return 1;
}
while ((ch = fgetc(fp)) != EOF) {
char_count++;
if(ch == ' ' || ch == '\t' || ch == '\0' || ch == '\n') {
if (in_word) {
in_word = 0;
word_count++;
}
return 0;
}
• Standard input stream is called "stdin" and is normally connected to the keyboard
• Standard output stream is called "stdout" and is normally connected to the display screen.
• Standard error stream is called "stderr" and is also normally connected to the screen.