Unit V Notes
Unit V Notes
Preprocessor:
Macro expansion: You can define macros, which are abbreviations for
C code, and then the C preprocessor will replace the macros with their
definitions throughout the program.
conditions.
Preprocessing directives are lines in your program that start with `#'.
1 #define
2 #include
3 #undef
4 #ifdef
5 #ifndef
6 #if
7 #else
8 #elif
9 #endif
Macro substitution directives in C are a powerful feature of the C preprocessor, a tool that
processes your source code before it is compiled. These directives allow you to define macros,
essentially shortcuts or replacements for code snippets. When the program is compiled, all
instances of the macro are replaced by its defined contents.
What is Macro in C?
A macro in C programming is a fragment of code that has been given a name. Whenever the
name is used, it is replaced by the contents of the macro. Macros are processed by the
preprocessor, a step that takes place before the actual compilation of code.
Defined using #define Directive: Macros are defined using the #define directive. For
example, #define PI 3.14159 defines a macro named PI.
No Storage Allocation: Unlike variables, macros don’t allocate storage space. They are
merely replacements done by the preprocessor.
Output:
Enter a & b
value 2 5
area of rectangle is 10
Miscellaneous Directives: (#undef)
the #undef directive tells the preprocessor to remove the definitions for the
specified macro. A macro can be redefined after it has been removed by
the #undef directive.
Syntax:
#undef Template_name(Arguments,...) (Expression)
Example:
# define (a*b) //macro definition
rectanglearea(a,b)
# undef rectanglearea(a,b) (a*b) //macro undefined
Example 1: Example 2:
#include<stdio.h> #include<stdio.h>
# define area(a,b) # define area(a,b)
(a*b) (a*b) # undef area(a,b)
# undef area(a,b) (a*b) # define area(a,b)
(a*b) (a*b)
int main() int main()
{ {
int a=2,b=11; int a=2,b=11;
printf("area of rectangle is printf("area of rectangle is
%d", area(a,b)); %d", area(a,b));
return 0; return 0;
} }
Output:
Output: area of rectangle is 22
Error // area is not defined macro
Conditional compilation : (#ifdef, #ifndef, #endif)
Syntax:
#ifdef
macron
ame
Stateme
nt 1;
Statement 1;
.
.
#endif
Example 1: Example 2:
#include<stdio.h> #include<stdio.h>
# define rectanglearea(a,b) # define rectanglearea(a,b)
(a*b) # define upper 2 (a*b) # define upper 2
int main() int main()
{ {
int a,b,area; int a,b,area;
#ifdef upper #ifdef u
printf("enter a & b value"); printf("enter a & b value");
scanf("%d%d",&a,&b); scanf("%d%d",&a,&b);
area=rectanglearea(a,b); area=rectanglearea(a,b);
printf("area of rectangle is %d",area); printf("area of rectangle is
#endif %d",area);
Printf(“\n end of the program”): #endif
return 0; Printf(“\n end of the program”):
} return 0;
}
Output:
enter a & b value Output:
57 end of the program
area of rectangle is
35 end of the program
Example:
#include<stdio.h>
# define
rectanglearea(a,b) (a*b) #
define upper 2
int main()
{
int a,b,area;
#ifndef upper
printf("enter a & b
value");
scanf("%d%d",&a,&
b);
area=rectanglearea(
a,b);
printf("area of rectangle is %d",area);
#endif
Printf(“\n end of the program”):
ret
urn
0;
}
Output:
end of the program
#include<stdio.h>
int main()
{
int num;
printf("enter number");
scanf("%d",&num);
#if num>0
printf("number is +ve\n");
#elif num<0
printf("number is -ve\n");
#else
printf("number is zero\n");
#endif
return 0;
}
Output:
Enter number
25
Number is +ve
File:
Types of Files
1. Text files
2. Binary files
3.
1. Text files
Text files are the normal .txt files that you can easily create using
Notepad or any simple text editors.
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.
2. Binary files
Instead of storing data in plain text, they store it in the binary form (0's
and 1's).
They can hold higher amount of data, are not readable easily and
provides a better security than text files.
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.
Syntax:
FILE
*file_pointer_name;
Example: FILE *fp;
unction description
filename is the name of the file to be opened and mode specifies the
purpose of opening the file. Mode can be of following types,
Example:
fp= fopen(“sample.txt”, “w”);
mode description
r opens a text file in reading mode
If fopen( ) cannot open "test.dat " it will a return a NULL pointer which
should always be tested for as follows.
Example:
FILE *fp ;
if ( ( fp = fopen( "test.dat", "r" ) ) == NULL )
{
puts( "Cannot open
file") ; exit( 1) ;
}
This will cause the program to be exited immediately if the file cannot
be opened.
Closing a File:
fclose(file_pointer_name);
Example:
fclose(fp); //fp is the file pointer associated with file to be closed
For reading and writing to a text file, we use the functions fprintf() and fscanf().
They are just the file versions of printf() and scanf(). The only difference
is that, fprint and fscanf expects a pointer to the structure FILE.
Writing to a text file:
#include<stdio.h>
Int main()
Int num;
FILE *fptr;
fptr = fopen("program.txt","w");
if(fptr == NULL)
printf("Error!");
exit(1);
scanf("%d",&num);
fprintf(fptr,"%d",num);
fclose(fptr);
return 0;
This program takes a number from user and stores in the file program.txt.
Functions fread() and fwrite() are used for reading from and writing to a
file on the disk respectively in case of binary files.
fwrite(address_data,size_data,numbers_data,pointer_to_file);
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
Now, inside the for loop, we store the value into the file using fwrite.
The first parameter takes the address of num and the second
parameter takes the size of the structure threeNum.
Since, we're only inserting one instance of num, the third parameter is
1. And, the last parameter *fptr points to the file we're storing the data.
fread(address_data,size_data,numbers_data,pointer_to_file);
int main()
{
int n;
struct threeNum num;
FILE *fptr;
return 0;
}
In this program, you read the same file program.bin and loop through
the records one by one.
In simple terms, you read one threeNum record of threeNum size from
the file pointed by *fptr into the structure num.
#include
<stdio.h> void
main()
{
FILE *fin, *fout ;
char dest[30], source[30], ch ;
fclose(
fin ) ;
fclose(
fout ) ;
}
Note : When any stream I/O function such as fgetc() is called the current
position of the file pointer is automatically moved on by the appropriate
amount, 1 character/ byte in the case of fgetc() ;
Append mode is used to append or add data to the existing data of file(if any).
Hence, when you open a file in Append(a) mode, the cursor is positioned at the
end of the present data in the file.
In general, to append is to join or add on to the end of something. For example,
an appendix is a section appended (added to the end) of a document. In computer
programming, append is the name of a procedure for concatenating (linked)
lists or arrays in some high- level programming languages.
Void main()
{
FILE *pFile; FILE
*pFile2; char
buffer[256];
pFile=fopen("myfile.txt", "r");
pFile2=fopen("myfile2.txt",
"a"); if(pFile==NULL) {
perror("Error opening file.");
}
else {
while(fgets(buffer, sizeof(buffer),
pFile)) { fprintf(pFile2, "%s", buffer);
}
fclose(pFile);
fclose(pFile2);
}
Unformatted data file refers to a category of file operations that reads or writes data as a
stream of bytes without regard to any format. Unformatted I/O in C is carried out with the aid
of functions like fread() and fwrite(). Without formatting, these operations are used to read and
write data directly to and from files.
Syntax:
Syntax for using the fwrite() function to print unformatted data:
fwrite(data, size, count, file pointer);
Here, count is the number of elements to be written, size is the size of each element to be
written, and the file pointer is a pointer to the file where the data will be written.
Syntax for using the fread() method with unformatted input:
fread(data, size, count, file pointer);
In this syntax, a pointer to the buffer where the data will be read, the size of each element to
be read, the number of elements to be read, and a pointer to the file from which the data will
be read.
Example
Let's examine an illustration of unformatted I/O in C:
#include <stdio.h>
int main() {
char data[100];
FILE *fp;
fp = fopen("file.txt", "w+");
fread(data, sizeof (
char), 100, fp);
printf("%s\n", data);
fclose(fp);
return 0;
}
Output:
This is an example of unformatted output
In C, there are a few distinctions between formatted and unformatted I/O. Some of these
variations include:
1. Unformatted file reads and writes data as a stream of bytes without any format,
whereas formatted file enables you to read and write data in a predefined format.
2. Flexibility: Formatted offers greater options for output formatting and data
representation, whereas unformatted offers less flexibility and is better suited to reading
3. Usability: Formatted is more user-friendly for straightforward input and output activities,
whereas unformatted necessitates more code and is better suited for intricate input and
output procedures.
Error Handling in C
C language does not provide any direct support for error handling. However a few methods and
variables defined in error.h header file can be used to point out error using the return statement
in a function. In C language, a function returns -1 or NULL value in case of any error and a
global variable errno is set with the error code. So the return value can be used to check error
while programming.
What is errno?
Whenever a function call is made in C language, a variable named errno is associated with it.
It is a global variable, which can be used to identify which type of error was encountered while
function execution, based on its value. Below we have the list of Error numbers and what does
they mean.
errno value Error
1 Operation not permitted
2 No such file or directory
3 No such process
4 Interrupted system call
5 I/O error
6 No such device or address
7 Argument list too long
8 Exec format error
9 Bad file number
10 No child processes
11 Try again
12 Out of memory
13 Permission denied
C language uses the following functions to represent error messages associated with errno:
perror(): returns the string passed to it along with the textual represention of the current
errno value.
strerror() is defined in string.h library. This method returns a pointer to the string
representation of the current errno value.
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main ()
{
FILE *fp;
/*
If a file, which does not exists, is opened,
we will get an error
*/
fp = fopen("IWillReturnError.txt", "r");
printf("Value of errno: %d\n ", errno);
printf("The error message is : %s\n", strerror(errno));
perror("Message from perror");
return 0;
}
Output
Value of errno: 2
The error message is: No such file or directory
Message from perror: No such file or directory
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
extern int errno;
void main()
{
char *ptr = malloc( 1000000000UL); //requesting to allocate 1gb memory space
if (ptr == NULL) //if memory not available, it will return null
{
puts("malloc failed");
puts(strerror(errno));
exit(EXIT_FAILURE); //exit status failure
}
else
{
free( ptr);
exit(EXIT_SUCCESS); //exit status Success
}
}
Here exit function is used to indicate exit status. Its always a good practice to exit a program
with a exit status. EXIT_SUCCESS and EXIT_FAILURE are two macro used to show exit
status. In case of program coming out after a successful operation EXIT_SUCCESS is used
to show successful exit. It is defined as 0. EXIT_Failure is used in case of any failure in the
program. It is defined as -1.
Sample Programs
int main()
{
FILE *fp;
char writestr[100];
// Read string to write
printf("Enter the string to write :");
gets(writestr);
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Driver code
int main()
{
FILE* ptr;
char ch;
if (NULL == ptr) {
printf("file can't be opened \n");
}
#include<stdio.h>
int main()
{
FILE *fp;
char ch;
fp = fopen("program.txt","r");
if(!fp)
{
printf("Error: File cannot be opened\n");
return 0;
}
//Move forward 6 bytes, thus we won't be seeing the first 6 bytes if we print till the end.
fseek(fp, 6, 0);
while(fread(&ch,sizeof(ch),1,fp)==1)
{
//Here, we traverse the entire file and print its contents until we reach its end.
printf("%c",ch);
}
fclose(fp);
return 0;
}