Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
7 views26 pages

Unit 5 Notes

The document covers structures and file management in C programming, detailing how to define, declare, and access structure members, as well as the use of unions. It explains the use of typedef for improved readability, array of structures, pointers to structures, and nested structures. Additionally, it discusses the differences between structures and unions, including memory management and initialization, along with examples of passing structures to functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views26 pages

Unit 5 Notes

The document covers structures and file management in C programming, detailing how to define, declare, and access structure members, as well as the use of unions. It explains the use of typedef for improved readability, array of structures, pointers to structures, and nested structures. Additionally, it discusses the differences between structures and unions, including memory management and initialization, along with examples of passing structures to functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

UNIT V STRUCTURES AND FILE MANAGEMENT 9

Structures: Defining a structure, Declaring structure variables, Accessing structure members,


Structure initialization, Array of structures, Pointer to structures, Union. File Management:
Defining and opening a file, closing a file, Input/output and Error Handling on Files.

STRUCTURES
Structure is a group of variables of different data types represented by a single name.

struct keyword to create a structure in C. The struct keyword is a short form of structured
data type.
Syntax:
struct struct_name {
DataType member1_name;
DataType member2_name;
DataType member3_name;

};

declare variable of a structure

struct struct_namevar_name;

or

struct struct_name {
DataType member1_name;
DataType member2_name;
DataType member3_name;

} var_name;

To access or modify members of a structure, we use the ( . ) dot operator


var_name.member1_name;
var_name.member2_name;

to assign values to structure members


5.1
V.S/C.S.B.S
There are three ways to do this.
1) Using Dot(.) operator

var_name.memeber_name = value;

2) All members assigned in one statement

struct struct_namevar_name =
{value for memeber1, value for memeber2 …so on for all the members}

e.g

#include <stdio.h>

// Defining a structure
struct A {
int x;
};

int main() {

// Creating a structure variable


struct A a;

// Initializing member
a.x = 11;

printf("%d", a.x);
return 0;
}

Output:
11

e.g

#include <stdio.h>

// Defining a structure to represent a student


struct Student {
5.2
V.S/C.S.B.S
char name[50];
int age;
float grade;
};

int main() {

// Declaring and initializing a structure


// variable
struct Student s1 = {"Ram",20, 18.5};

// Designated Initializing another stucture


struct Student s2 = {.age = 18, .name =
"Krish", .grade = 22};

// Accessing structure members


printf("%s\t%d\t%.2f\n", s1.name, s1.age, s1.grade);
printf("%s\t%d\t%.2f\n", s2.name, s2.age, s2.grade);

return 0;
}
Output
Ram 20 18.50
Krish 18 22.00

Uses of Structure in C
C structures are used for the following:

 The structure can be used to define the custom data types that can be used to create some complex data
types such as dates, time, complex numbers, etc. which are not present in the language.
 It can also be used in data organization where a large amount of data can be stored in different fields.
 Structures are used to create data structures such as trees, linked lists, etc.
 They can also be used for returning multiple values from a function.

Use of typedef in Structure


typedef makes the code short and improves readability. In the above discussion we have seen that while
using structs every time we have to use the lengthy syntax, which makes the code confusing, lengthy,
complex and less readable. The simple solution to this issue is use of typedef. It is like an alias of struct.

Code without typedef Code using tyepdef

struct home_address { typedef struct home_address{


int local_street; int local_street;
char *town; char *town;
char *my_city; char *my_city;
char *my_country; char *my_country;
}; }addr;
... ..
struct home_address var; ..
var.town = "Agra"; addr var1;
var.town = "Agra";

Example of typedef

#include <stdio.h>
#include <string.h>
5.3
V.S/C.S.B.S
// struct with typedef rectangle
typedef struct rectangle {
int length;
int breath;
} rectangle;

int main() {

rectangle r1;

r1.length = 19;
r1.breath = 25;

// print struct variables


printf("Length Of rectangle is : %d\n", r1.length);
printf("Breath Of rectangle is: %d\n", r1.breath);

return 0;
}

OUTPUT:
Length Of rectangle is : 19
Breath Of rectangle is: 25

Copy Structure
Copying structure is simple as copying any other variables. For example, s1 is copied into s2 using
assignment operator.

s2 = s1;

example:
#include <stdio.h>

struct Student {
int id;
char grade;
};

int main() {
struct Student s1 = {1, 'A'};

// Create a copy of student s1


struct Student s2 = s1;

printf("Student 2 ID: %d\n", s2.id);


printf("Student 2 Grade: %c", s2.grade);
printf("\nStudent 1 ID: %d\n", s1.id);
printf("Student 1 Grade: %c\n", s1.grade);
s2.grade='B';
printf("after changing s2 grade\n\n\n");
printf("Student 2 ID: %d\n", s2.id);
printf("Student 2 Grade: %c", s2.grade);

5.4
V.S/C.S.B.S
printf("\nStudent 1 ID: %d\n",
n", s1.id);
printf("Student 1 Grade: %c\n",
n", s1.grade);

return 0;
}

OUTPUT:
Student 2 ID: 1
Student 2 Grade: A
Student 1 ID: 1
Student 1 Grade: A

after changing s2 grade

Student 2 ID: 1
Student 2 Grade: B
Student 1 ID: 1
Student 1 Grade: A
Note: in the above example , changing the grade of s2 does not change s1.

Array of Structures in C
An array of structures is an array with structure as elements.

For example:
Here, stu[5] is an array of structures. This array has 5 elements and these elements are structures of the
same type “student”. The element s[0] will store the values such as name, rollNum, address & marks of a
student, similarly element s[1] will store these details for another student and so on.

struct student {
char name[60];
int rollNum;
char address[60];
float marks;
} stu[5];

Designated initialization is a basic initialization of structure members that is typically used when
we only want to initialise a few structure members rather than all of them.

e.g

5.5
V.S/C.S.B.S
#include <stdio.h>
struct numbers
{
int num1, num2;
};
int main()
{
// Assignment using using designated initialization
struct numbers s1 = {.num2 = 22, .num1 = 11};
struct numbers s2 = {.num2 = 30};//num1 of s2 not initialized

printf ("num1: %d, num2: %d\n", s1.num1, s1.num2);


printf ("num1: %d", s2.num2);
return 0;
}

Structure Pointer
A pointer to a structure allows us to access structure members using the ( -> ) arrow operator instead of
the dot operator.

#include <stdio.h>

// Structure declaration
struct Point {
int x, y;
};

int main() {
struct Point p = { 1, 2 };

// ptr is a pointer to structure p


struct Point* ptr = &p;

// Accessing structure members using structure pointer


printf("%d %d", ptr->x, ptr->y);

return 0;
}
OUTPUT:
1 2

Nested Structures in C
The term "nested" refers to the act of placing or storing one thing inside another. Because structure in C is
a user-defined data type, we can specify another structure as its data member when creating a structure,
resulting in a structure with another structure inside it. The nested structure can also have stacked
structures.

e.g

#include <stdio.h>

5.6
V.S/C.S.B.S
// Child structure declaration
struct child {
int x;
char c;
};

// Parent structure declaration


struct parent {
int a;
struct child b; // child struct is a member of parent struct
};

int main() {
struct parent p = { 25, 195, 'A' };

// Accessing and printing nested members


printf("p.a = %d\n", p.a);
printf("p.b.x = %d\n", p.b.x);
printf("p.b.c = %c", p.b.c);
return 0;
}

Self Referential Structures

Self Referential structures are those structures that have one or more pointer
pointerss which point to the same
type of structure, as their member.

#include <stdio.h>

struct node {
int data1;
char data2;
struct node* link;
};

int main()
{
struct node ob1; // Node1

// Initialization

5.7
V.S/C.S.B.S
ob1.link = NULL;
ob1.data1 = 10;
ob1.data2 = 20;

struct node ob2; // Node2

// Initialization
ob2.link = NULL;
ob2.data1 = 30;
ob2.data2 = 40;

// Linking ob1 and ob2


ob1.link = &ob2;

// Accessing data members of ob2 using ob1


printf("%d", ob1.link->data1);
printf("\n%d", ob1.link->data2);
return 0;
}

Output
3040

UNION

union is a user-defined data type that can contain elements of the different data types just like structure.
But unlike structures, all the members in the C union are stored in the same memory location. Due to this,
only one member can store data at the given point in time.

C Union Declaration
In this part, we only declare the template of the union, i.e., we only declare the members’ names and data
types along with the name of the union. No memory is allocated to the union in the declaration.

union name {
type1 member1;
type2 member2;
.
.
};

Create a Union Variable


We need to define a variable of the union type to start using union members. There are two methods using
which we can define a union variable:

Creating Union Variable with Declaration

5.8
V.S/C.S.B.S
union name{
type member1;
type member2;

} var1, var2, …;

Creating Union Variable after Declaration

union name var1, var2, var3…;

where name is the name of an already declared union.

Access Union Members


We can access the members of a union by using the ( . ) dot operator just like structures.

var1.member1;

where var1 is the union variable and member1 is the member of the union.

Initialize Union
The initialization of a union is the initialization of its members by simply assigning the value to it.

var1.member1 = val;

example:

#include <stdio.h>

// Declaring multiple unions


union A{
int x;
char y;
};

union B{
int arr[10];
char y;
};

int main() {

// Finding size using sizeof() operator


printf("Sizeof A: %ld\n", sizeof(union A));
printf("Sizeof B: %ld\n", sizeof(union B));

return 0;
}

OUTPUT:

5.9
V.S/C.S.B.S
Sizeof A: 4
Sizeof B: 40

Example

#include <stdio.h>

// Define a union named MyUnion


union MyUnion {
int intValue;
float floatValue;
char stringValue[20];
};

int main() {
// Declare an instance of the union
union MyUnion data;

// Assign values to different members of the uunion


data.intValue = 42;
printf("Integer Value: %d\n",
n", data.intValue);

data.floatValue = 3.14;
printf("Float Value: %.2f\n",
n", data.floatValue);

// Assign a string to the union


strcpy(data.stringValue, "Hello, Union!");
printf("String Value: %s\n",
n", data.stringValue);

5.10
V.S/C.S.B.S
return 0;
}

OUTPUT:
Integer Value: 42
Float Value: 3.14
String Value: Hello, Union!

Difference between C Union and C Structure


Feature C Union C Structure
Memory
Shares memory space among all members. Each member has its memory space.
Allocation
Shares memory, using the largest member's Requires memory for each member
Memory Usage
size. simultaneously.
Accessing
Members share the same memory space. Members are accessed individually.
Members
Size is the size of the largest member.
Size Calculation Size is the sum of sizes of its members.
No wastage as it uses the size of the largest
Memory Wastage Can lead to memory wastage for small types.
member.
All members share the same memory, so
Initialization Each member can be initialized separately.
initializing one affects others.
Suitable when only one of the data types is
Usage Suitable when different data types are needed.
used at a time to save memory.
union student struct student
{ {
Example int id; int id;
char name[12]; char name[12];
}; };

Nested Union

add unions inside a union

example:
#include <stdio.h>

union Union1
{
int a;
char b;
};

union Union2
{
float x;
union Union1 nestedUnion;
};

int main()
{
union Union2 u;

u.nestedUnion.a = 10;
5.11
V.S/C.S.B.S
printf("Value of a: %d\n", u.nestedUnion.a);

u.x = 3.14;
printf("Value of x: %.2f\n", u.x);

u.nestedUnion.b = 'A';
printf("Value of b: %c\n", u.nestedUnion.b);

return 0;
}

OUTPUT:
Value of a: 10
Value of x: 3.14
Value of b: A

Union inside a structure

#include <stdio.h>
struct Employee
{
int empID;
char empName[20];
union
{
float hourlyRate;
int monthlySalary;
} payment;
};
int main()
{
struct Employee emp1;
emp1.empID = 101;
strcpy(emp1.empName, "Sunil");
emp1.payment.hourlyRate = 15.5;
printf("Hourly rate: %.2f\n", emp1.payment.hourlyRate);
emp1.payment.monthlySalary = 5000;
printf("Monthly salary: %d\n", emp1.payment.monthlySalary);
return 0;
}

OUTPUT:
Hourly rate: 15.50
Monthly salary: 5000

Passing Structure as function parameter

When passing structures to or from functions in C, it is important to keep in mind that the entire structure
will be copied. This can be expensive in terms of both time and memory, especially for large structures.
The passing of structure to the function can be done in two ways:

5.12
V.S/C.S.B.S
 By passing all the elements to the function individually.
 By passing the entire structure to the function.

Example 1 : call by value

// C program to pass structure as an argument to the


// functions using Call By Value Method
#include <stdio.h>

struct car {
char name[30];
int price;
};

void print_car_info(struct car c)


{
printf("Name : %s", c.name);
printf("\nPrice : %d\n", c.price);
}

int main()
{
struct car c = { "Tata", 1021 };
print_car_info(c);
return 0;
}
OUTPUT:
Name : Tata
Price : 1021

Example 2: Call by reference

// C program to pass structure as an argument to the


// functions using Call By referenc Method uses pointer to structure and
//passes address of the structure
#include <stdio.h>

struct car {
char name[30];
int price;
};

void print_car_info(struct car *c)


{
printf("Name : %s", c->name);
printf("\nPrice : %d\n", c->price);
}

int main()
{
struct car c = { "Tata", 1021 };
print_car_info(&c);
return 0;

5.13
V.S/C.S.B.S
}
OUTPUT
Name : Tata
Price : 1021

Return a Structure From functions


We can return a structure from a function using the return Keyword. To return a structure from a function
the return type should be a structure only.

// C program to return a structure from a function


#include <stdio.h>

struct student {
char name[20];
int age;
float marks;
};

// function to return a structure


struct student get_student_data()
{
struct student s;

printf("Enter name: ");


scanf("%s", s.name);
printf("Enter age: ");
scanf("%d", &s.age);
printf("Enter marks: ");
scanf("%f", &s.marks);

return s;
}

int main()
{
// structure variable s1 which has been assigned the
// returned value of get_student_data
struct student s1 = get_student_data(); // return value is assigned to the structure
// displaying the information
printf("Name: %s\n", s1.name);
printf("Age: %d\n", s1.age);
printf("Marks: %.1f\n", s1.marks);

return 0;
}

OUPUT:
Enter name: ram
Enter age: 32
Enter marks: 78

Name: ram
Age: 32
5.14
V.S/C.S.B.S
Marks: 78.0
File Handling in C
File handling in C is the process in which we create, open, read, write, and close operations on a file. C
language provides different functions such as fopen(), fwrite(), fread(), fseek(), fprintf(), etc. to perform
input, output, and many different C file operations in our program.

Need of file handling


In order to understand why file handling is important, let us look at a few features of using files:

 Reusability: The data stored in the file can be accessed, updated, and deleted anywhere and
anytime providing high reusability.
 Portability: Without losing any data, files can be transferred to another in the computer system.
The risk of flawed coding is minimized with this feature.
 Efficient: A large amount of input may be required for some programs. File handling allows you
to easily access a part of a file using few instructions which saves a lot of time and reduces the
chance of errors.
 Storage Capacity: Files allow you to store a large amount of data without having to worry
wo about
storing everything simultaneously in a program.

Types of Files in C
A file can be classified into two types based on the way the file stores the data. They are as follows:

 Text Files
 Binary Files

C File Operations
C file operations refer to the different possible operations that we can perform on a file in C such as:

function purpose
fopen () Creating a file or opening an existing file
fclose () Closing a file
fprintf () Writing a block of data to a file
fscanf () Reading a block data from a file
getc () Reads a single character from a file
putc () Writes a single character to a file
getw () Reads an integer from a file
putw () Writing an integer to a file
Sets the position of a file pointer to a specified
fseek ()
location
5.15
V.S/C.S.B.S
function purpose
ftell () Returns the current position of a file pointer
rewind () Sets the file pointer at the beginning of a file

A file pointer is a reference to a particular position in the opened file. It is used in file handling to
perform all file operations such as read, write, close, etc. We use the FILE macro to declare the file
pointer variable. The FILE macro is defined inside <stdio.h> header file.

Syntax of File Pointer

FILE* pointer_name;

1. Opening a file
fopen() function is used for opening a file.
Syntax:

FILE pointer_name = fopen ("file_name", "Mode");


pointer_name can be anything of your choice.
file_name is the name of the file, which you want to open. Specify the full path here like
“C:\\myfiles\\newfile.txt”.

While opening a file, you need to specify the mode. The mode that we use to read a file is “r” which is
“read only mode”.
for example:

FILE *fp;
fp = fopen("C:\\myfiles\\newfile.txt", "r");
The address of the first character is stored in pointer fp.

How to check whether the file has opened successfully?


If file does not open successfully then the pointer will be assigned a NULL value, so you can write the
logic like this:
This code will check whether the file has opened successfully or not. If the file does not open, this will
display an error message to the user.

..
FILE fpr;
fpr = fopen("C:\\myfiles\\newfile.txt", "r");
if (fpr == NULL)
{
puts("Error while opening file");
exit();
}
Various File Opening Modes:
The file is opened using fopen() function, while opening you can use any of the following mode as per the
requirement.
Mode “r”: It is a read only mode, which means if the file is opened in r mode, it won’t allow you to write
and modify content of it. When fopen() opens a file successfully then it returns the address of first
character of the file, otherwise it returns NULL.

Mode “w”: It is a write only mode. The fopen() function creates a new file when the specified file doesn’t
exist and if it fails to open file then it returns NULL.
5.16
V.S/C.S.B.S
Mode “a”: Using this mode Content can be appended at the end of an existing file. Like Mode “w”,
fopen() creates a new file if it file doesn’t exist. On unsuccessful open it returns NULL.
File Pointer points to: last character of the file.

Mode “r+”: This mode is same as mode “r”; however you can perform various operations on the file
opened in this mode. You are allowed to read, write and modify the content of file opened in “r+” mode.
File Pointer points to: First character of the file.

Mode “w+”: Same as mode “w” apart from operations, which can be performed; the file can be read,
write and modified in this mode.
Mode “a+”: Same as mode “a”; you can read and append the data in the file, however content
modification is not allowed in this mode.

2. Reading a File
To read the file, we must open it first using any of the mode, for example if you only want to read the file
then open it in “r” mode. Based on the mode selected during file opening, we are allowed to perform
certain operations on the file.

C Program to read a file


fgetc( ): This function reads the character from current pointer’s position and upon successful read moves
the pointer to next character in the file. Once the pointers reaches to the end of the file, this function
returns EOF (End of File). We have used EOF in our program to determine the end of the file.

#include <stdio.h>
int main()
{
/* Pointer to the file */
FILE *fp1;
/* Character variable to read the content of file */
char c;

/* Opening a file in r mode*/


fp1= fopen ("C:\\myfiles\\newfile.txt", "r");

/* Infinite loop –I have used break to come out of the loop*/


while(1)
{
c = fgetc(fp1);
if(c==EOF)
break;
else
printf("%c", c);
}
fclose(fp1);
return 0;
}
3. Writing to a file
To write the file, we must open the file in a mode that supports writing. For example, if you open a file in
“r” mode, you won’t be able to write the file as “r” is read only mode that only allows reading.

Example: C Program to write the file

5.17
V.S/C.S.B.S
This program asks the user to enter a character and writes that character at the end of the file. If the file
doesn’t exist then this program will create a file with the specified name and writes the input character
into the file.

#include <stdio.h>
int main()
{
char ch;
FILE *fpw;
fpw = fopen("C:\\newfile.txt","w");

if(fpw == NULL)
{
printf("Error");
exit(1);
}

printf("Enter any character: ");


scanf("%c",&ch);

/* You can also use fputc(ch, fpw);*/


fprintf(fpw,"%c",ch);
fclose(fpw);

return 0;
}
4. Closing a file
fclose(fp);
The fclose( ) function is used for closing an opened file. As an argument you must provide a pointer to the
file that you want to close.

An example to show Open, read, write and close operation in C


#include <stdio.h>
int main()
{
char ch;

/* Pointer for both the file*/


FILE *fpr, *fpw;
/* Opening file FILE1.C in “r” mode for reading */
fpr = fopen("C:\\file1.txt", "r");

/* Ensure FILE1.C opened successfully*/


if (fpr == NULL)
{
puts("Input file cannot be opened");
}

/* Opening file FILE2.C in “w” mode for writing*/


fpw= fopen("C:\\file2.txt", "w");

/* Ensure FILE2.C opened successfully*/


if (fpw == NULL)
{
5.18
V.S/C.S.B.S
puts("Output file cannot be opened");
}

/*Read & Write Logic*/


while(1)
{
ch = fgetc(fpr);
if (ch==EOF)
break;
else
fputc(ch, fpw);
}

/* Closing both the files */


fclose(fpr);
fclose(fpw);

return 0;
}
How to read/ write (I/O) Strings in Files – fgets&fputs

char *fgets(char *s, int rec_len, FILE *fpr)


s: Array of characters to store strings.
rec_len: Length of the input record.
fpr: Pointer to the input file.
Lets take an example:

Example to read the strings from a file in C programming


#include <stdio.h>
int main()
{
FILE *fpr;
/*Char array to store string */
char str[100];
/*Opening the file in "r" mode*/
fpr = fopen("C:\\mynewtextfile.txt", "r");

/*Error handling for file open*/


if (fpr == NULL)
{
puts("Issue in opening the input file");
}

/*Loop for reading the file till end*/


while(1)
{
if(fgets(str, 10, fpr) ==NULL)
break;
else
printf("%s", str);
}
/*Closing the input file after reading*/
fclose(fpr);
return 0;
5.19
V.S/C.S.B.S
}
In the above example we have used fgets function like this:

fgets(str, 10, fpr)

Here str represents the string (array of char) in which you are storing the string after reading it from file.
10 is the length of the string that needs to be read every time.
fpr is pointer to file, which is going to be read.

Why I used if(fgets(str, 10, fpr)==NULL as a logic to determine end of the file?
In the above examples, we have used ch==EOF to get to know the end of the file. Here we have used this
logic because fgets returns NULL when there is no more records are available to be read.

C Program – Writing string to a file


int fputs( const char * s, FILE * fpw );
char *s – Array of char.
FILE *fpw – Pointer (of FILE type) to the file, which is going to be written.

#include <stdio.h>
int main()
{
FILE *fpw;

/*Char array to store strings */


char str[100];

/*Opening the file FILEW.TXT in "w" mode for writing*/


fpw = fopen("C:\\mynewtextfile2.txt", "w");

/*Error handling for output file*/


if (fpw== NULL)
{
puts("Issue in opening the Output file");
}

printf("Enter your string:");

/*Stored the input string into array – str*/


gets(str);

/* Copied the content of str into file –


* mynewtextfile2.txt using pointer – fpw
*/
fputs(str, fpw);

/*Closing the Output file after successful writing*/


fclose(fpw);
return 0;
}
fputs takes two arguments –

fputs(str, fpw)
str – str represents the array, in which string is stored.
fpw – FILE pointer to the output file, in which record needs to be written.
5.20
V.S/C.S.B.S
Point to note about fputs:
fputs by default doesn’t add new line after writing each record, in order to do that manually – you can
have the following statement after each write to the file.

fputs("\n", fpw);

C FILE I/O for Binary files

So far, we have learned file operations on text files, what if the files are binary (such as .exe file). The
above programs will not work for binary files, however there is a minor change in handling Binary files.
The main difference is the file name & modes. Lets understand this with the help of an example. Lets say
I have two binary files bin1.exe & bin2.exe – I want to copy content of bin1.exe to bin2.exe:

Example: Reading and Writing Binary Files in C


#include <stdio.h>
int main()
{
char ch;

/* Pointers for both binary files*/


FILE *fpbr, *fpbw;

/* Open for bin1.exe file in rb mode */


fpbr = fopen("bin1.exe", "rb");

/* test logic for successful open*/


if (fpbr == NULL)
{
puts("Input Binary file is having issues while opening");
}

/* Opening file bin2.exe in “wb” mode for writing*/


fpbw= fopen("bin2.exe", "wb");

/* Ensure bin2.exe opened successfully*/


if (fpbw == NULL)
{
puts("Output binary file is having issues while opening");
}

/*Read & Write Logic for binary files*/


while(1)
{
ch = fgetc(fpbr);
if (ch==EOF)
break;
else
fputc(ch, fpbw);
}

/* Closing both the binary files */


fclose(fpbr);
fclose(fpbw);
5.21
V.S/C.S.B.S
return 0;
}
---------------------------
Preprocessor directives

Preprocessor directives in C are ins


instructions
tructions to the preprocessor, a part of the compiler, that
modify the source code before it is compiled. They are used for tasks like including files,
defining macros, and conditional compilation. Directives are recognizable by the '#' symbol at
the beginning of the line.

Types of pre-processor
processor directives

5.22
V.S/C.S.B.S
#include
#include preprocessor directive is used to include the contents of a specified file into the
source code before compilation. It allows you to use functions, constants, and variables from
external libraries or header files. There are two types:
#include <file_name>

#include "filename"
Here, file inclusion with double quotes ( ” ” ) tells the compiler to search for the header file in
the directory of source filewhile <> is used for system libraries.

How to create user defined header file:

Step 1. Create a own header file (let say MyHeader.h) and store it a folder ( say C:\
MyHeader.)

MyHeader.h

#include<stdio.h>
void add(int a, int b)
{
printf("Added value=%d\n", a + b);
}
void multiply(int a, int b)
{
printf("Multiplied value=%d\n", a * b);
}

Step 2: Create a C program ( say MyProgram.c) and store it in the same folder where the header file created
in step 1 ( say C:\ MyProgram.c). in this C program include the MyHeader.h as shown below:

MyProgram.c
#include <stdio.h>
#include "MyHeader.h"
int main()
{
add(4, 6);

/*This calls add function written in MyHeader.h */

multiply(5, 5);

// Same for the multiply function in MyHeader.h

printf("End");
return 0;
}

5.23
V.S/C.S.B.S
Step 3: go to the command prompt and type as follows:

C;\> gcc MyProgram.c MyHeader.h –o MyProgam.exe

You will get the output:

-----------------------------------------------

#define
#define is a preprocessor directive used to define macros, which are essentially text
substitutions performed during compilation

#include <stdio.h> #include <stdio.h> #include <stdio.h>


#define PI 3.14 #define PI 3.14 #define number 15
main() #undef PI int square=number*number;
{ main() { #undef number
printf("%f",PI); printf("%f",PI); main() {
} } printf("%d",square);
}
o/p: 3.14 o/p error o/p 225

#if, #ifdef, #else, #elif, #endif


The above directives are Conditional Compilation directives that help to compile a specific
portion of the program or let us skip compilation of some specific part of the program based on
some conditions.
e.g
#include <stdio.h>

int main() {
#define VALUE 2

// Check if VALUE is greater than 3


#if VALUE > 3
printf("Value is greater than 3\n");

// Check if VALUE is 3
#elif VALUE == 3
printf("Value is 3");

// If neither conditions are true, this


// block will execute
#else
printf("Value is less than or equal to 2");
#endif

return 0;
}
o/p : Value is less than or equal to 2

5.24
V.S/C.S.B.S
command-line arguments

In C programming, command-line arguments allow users to pass data to a program when it's
executed from the command line. This data is accessed within the main() function using
the argc and argv parameters.

To pass command-line arguments, we typically define main() with two arguments: the first
argument is the number of command-line arguments and the second is a list of command-
line arguments.
Syntax
int main(int argc, char *argv[]) { /* ... */ }
or
int main(int argc, char **argv) { /* ... */ }
Here,
 argc (ARGument Count) is an integer variable that stores the number of command-line
arguments passed by the user including the name of the program. So if we pass a value to a
program, the value of argc would be 2 (one for argument and one for program name)
 The value of argc should be non-negative.
 argv (ARGument Vector) is an array of character pointers listing all the arguments.
 If argc is greater than zero, the array elements from argv[0] to argv[argc-1] will contain
pointers to strings.
 argv[0] is the name of the program , After that till argv[argc-1] every element is command -
line arguments.
Example: lets create a c program argc1.c
#include <stdio.h>
// main function with argc (argument count) and argv (argument vector)
int main(int argc, char *argv[]) {
// Check the number of arguments passed
int i,sum=0;
printf("Number of arguments: %d\n", argc);
// Loop through and print each argument
for(i = 0; i < argc; i++) {
printf("Argument %d: %s\n", i, argv[i]);
sum += atoi(argv[i]);
}
printf("SUM is %d",sum);
return 0;
}

Compile the above program from command line as shown below:

5.25
V.S/C.S.B.S
E:\C_programming>gcc argc1.c -o argc1.exe

E:\C_programming>argc1.exe 1 3 5 6 7
Number of arguments: 6
Argument 0: argc1.exe
Argument 1: 1
Argument 2: 3
Argument 3: 5
Argument 4: 6
Argument 5: 7
SUM is 22

------------------------------

5.26
V.S/C.S.B.S

You might also like