En3es28 - Apc Lab Manual
En3es28 - Apc Lab Manual
INDORE
DEPARTMENT
OF
COMPUTER SCIENCE & ENGINEERING
Lab Manual
Course: Advance Programming With C
Session: 2023-24
INDEX
S. Experiment Page
No No
1 Program to create, initialize, assign and access a pointer variable.
2 Program to swap two numbers using pointers.
3 Program to change the value of constant integer using pointers
4 Program to print a string using pointer.
5 Program to count vowels and consonants in a string using pointer.
6 Program to find sum of elements of array using pointer.
7 Program to Compare strings using pointer
8 Program to Find smallest number in array using pointer
9 Program to Find largest element in array using pointer.
10 Program to create a pointer array store elements in it and display
11 Program to demonstrate function pointers
12 Program to perform Addition Subtraction Multiplication Division using array of function
pointers.
13 Program to display details of student two (Name, roll no, marks) using structure.
14 Program to display details of employee using array of structure.
15 Program to access member of structures using pointers.
16 Program for passing structure to a function.
17 Program for returning a structure from a function
18 Program to display details of student two (Name, roll no, marks) with the help of union.
19 Program to demonstrate malloc and calloc.
20 Program to allocate memory of array at run time.
21 Program to print the day of week and month of a year
22 Program to calculate area of circle using macro
23 Program to calculate area of circle using macro
24 Program to create a header file and use it in a program.
25 Program to demonstrate file operation. a. Creating a new file b. Opening an existing file c.
Closing a file d. Reading from and writing information to a file
26 Program to count number of words, number of character and number of lines from a given
text file.
27 Program in C to delete a specific line from a file.
28 Write a program in C to copy a file in another name.
29 Write a program in C to merge two files and write it in a new file.
30 Write a program in C to encrypt a text file.
31 Write a program in C to decrypt a previously encrypted file
32 Write a program in C to remove a file from the disk
33 Write a program to draw a circle and fill blue color in it.
34 Write a program to move a circle using suitable animations.
Objective
Understand the concept pointer initialization and declaration.
Theory
The pointer is a variable which stores the address of another variable. This variable can be of type
int, char, array, function, or any other pointer. The size of the pointer depends on the architecture.
However, in 32-bit architecture the size of a pointer is 2 byte.
Consider the following example to define a pointer which stores the address of an
integer.
int n = 10;
int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type
integer.
Program
int main()
{
int num; /*declaration of integer variable*/
int *pNum; /*declaration of integer pointer*/
return 0;
}
Objective (s):
To Understand the concept how call by reference.
Theory
Call by reference method copies the address of an argument into the formal parameter. In this
method, the address is used to access the actual argument used in the function call. It means that
changes made in the parameter alter the passing argument. In this method, the memory allocation
is the same as the actual parameters. All the operations in the function are performed on the value
stored at the address of the actual parameter, and the modified value will be stored at the same
address. Means, both the actual and formal parameters refer to same locations, so any changes
made inside the function are actually reflected in actual parameters of caller.
Program
#include <stdio.h>
int main()
{
int num1,num2;
return 0;
}
OUTPUT
Objective:
Understand the concept of constant integer and pointer.
Theory
A constant in C language is a value that remains constant throughout the program and cannot be
changed during program execution. Constants in C can be of many types, including integer
constants, character constants, floating point constants, arithmetic constants, and array constants.
In other words, they are used in programs to represent constant values that will not change. For
example, if you're working on a program that requires a ‘Pi’ value, you can define ‘Pi’ as a
constant so its value doesn't change while the program is running.
Program
#include <stdio.h>
int main()
{
const int a=10; //declare and assign constant integer
int *p; //declare integer pointer
p=&a; //assign address into pointer p
return 0;
}
1. What is constant.
2. What is constant pointer.
3.
Objective:
Understand the concept of Array, String and Pointer.
Theory
The string itself act as a pointer. The string name is a pointer to the first character in the string.
Program
#include <stdio.h>
int main()
{
char str[100];
char *ptr;
return 0;
}
OUTPUT
Objective
Program to count vowels and consonants in a string using pointer.
Theory
In this program, our task is to count the total number of vowels and consonants present in the
given string. As we know that, the characters a, e, i, o, u are known as vowels in the English
alphabet. Any character other than that is known as the consonant.
Program
#include <stdio.h>
#include <string.h>
int main()
{
char s[1000],*p;
int vowels=0,consonants=0;
printf("Enter the string : ");
gets(s);
p=s;
while(*p!='\0')
{
if( (*p>=65 && *p<=90) || (*p>=97 && *p<=122))
{
if(*p=='a'|| *p=='e'||*p=='i'||*p=='o'||*p=='u'||*p=='A'||*p=='E'||*p=='I'||*p=='O' ||*p=='U')
vowels++;
else
consonants++;
}
p++;
}
printf("vowels = %d\n",vowels);
printf("consonants = %d\n",consonants);
return 0;
}
Objective
Understand the concept of array and Pointer.
Theory
Arrays and pointers are closely related in C. In fact an array declared as int A[10]; can be accessed
using its pointer representation. The name of the array A is a constant pointer to the first element
of the array. So, A can be considered a const int*. Since A is a constant pointer, A = NULL would
be an illegal statement. Arrays and pointers are synonymous in terms of how they use to access
memory. But, the important difference between them is that, a pointer variable can take different
addresses as value whereas, in case of array it is fixed.
Program
int main() {
int arr[100], size;
int *ptr, sum = 0;
printf("Enter the size of the array: ");
scanf("%d", &size);
printf("Enter array elements: ");
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}
// Set address of first array element to *ptr
ptr = arr;
for (int i = 0; i < size; i++) {
sum = sum + *ptr;
ptr++; // Increment pointer by one to get next element
}
printf("The sum of array elements is: %d", sum);
return 0;
}
Objective
Compare string using pointer.
Theory
Program
#include <stdio.h>
int main()
{
char string1[50],string2[50],*str1,*str2;
int i,equal = 0;
printf("Enter The First String: ");
gets(string1);
printf("Enter The Second String: ");
gets(string2);
str1 = string1;
str2 = string2;
while(*str1 == *str2)
{
if ( *str1 == '\0' || *str2 == '\0' )
break;
str1++;
str2++;
}
if( *str1 == '\0' && *str2 == '\0' )
printf("\n\nBoth Strings Are Equal.");
else
printf("\n\nBoth Strings Are Not Equal.");
}
Objective
To Find smallest number in array using pointer.
Theory
We ask the user to input N integer numbers and store it inside a[N]. Next, we assign base address
to pointer variable small. Next, we iterate through the array elements one by one using a for loop,
and check if any of the elements of the array is smaller than whatever the value present at *small.
If there is any element smaller than *small, we assign that value to *small. Once the control exits
the for loop, we print the value present in pointer variable *small, which holds the smallest
element in the array.
Program
#include<stdio.h>
void main()
{
int i,*ptr, n,a[100],small;
printf("Enter How many number you want?:\n") ;
scanf("%d",&n) ;
printf("Enter %d numbers\n",n) ;
for(i=0;i<n;i++)
{
scanf("%d",&a[i]) ;
}
ptr = a;
small= *ptr;
for(i=0;i<n;i++)
{
if(*ptr<small)
{
small=*ptr;
}
*ptr++;
}
printf("Smallest Number is : %d",small);
}
Objective
To Find largest element in array using pointer.
Theory
.
Program
#include<stdio.h>
int main()
{
int i,*ptr, n,a[100],max;
printf("Enter %d numbers\n",n) ;
for(i=0;i<n;i++)
{
scanf("%d",&a[i]) ;
}
ptr = a;
max= *ptr;
for(i=0;i<n;i++)
{
if(*ptr>max)
{
max=*ptr;
}
*ptr++;
}
printf("Largest Number is : %d",max);
return 0;
}
Objective
Program to create a pointer array store elements in it and display.
Theory
Program
#include <stdio.h>
int main() {
int data[5];
printf("Enter elements: ");
for (int i = 0; i < 5; ++i)
scanf("%d", data + i);
OUTPUT
Objective
Program to demonstrate function pointers
Theory
The pointer variable that holds a function’s address is called a function pointer. The basic
advantage of a function pointer is that one function can be passed as a parameter to another
function. Function pointer calls are faster than normal functions. The code of a function always
resides in memory, which means that the function has some address. We can get the address of
memory by using the function pointer.
For example:
Program
#include <stdio.h>
int add(int,int);
int main()
{
int a,b;
int (*ip)(int,int);
int result;
printf("Demonstration of function Pointer\n");
printf("Enter the values of a and b : ");
scanf("%d %d",&a,&b);
ip=add;
result=(*ip)(a,b);
printf("Value after addition is : %d",result);
return 0;
}
int add(int a,int b)
Department of Computer Science Engineering
Faculty of Engineering
Medi-Caps University
21
{
int c=a+b;
return c;
}
OUTPUT
Objective
Program to perform Addition Subtraction Multiplication Division using array of function pointers.
Theory
Function pointers are used in those applications where we do not know in advance which function
will be called. In an array of function pointers, array takes the addresses of different functions, and
the appropriate function will be called based on the index number.
Program
#include <stdio.h>
float add(float,int);
float sub(float,int);
float mul(float,int);
float div(float,int);
int main()
{
float x; // variable declaration.
int y;
float (*fp[4]) (float,int); // function pointer declaration.
fp[0]=add; // assigning addresses to the elements of an array of a function pointer.
fp[1]=sub;
fp[2]=mul;
fp[3]=div;
printf("Enter the values of x and y :");
scanf("%f %d",&x,&y);
float r=(*fp[0]) (x,y); // Calling add() function.
printf("\nSum of two values is : %f",r);
r=(*fp[1]) (x,y); // Calling sub() function.
printf("\nDifference of two values is : %f",r);
r=(*fp[2]) (x,y); // Calliung sub() function.
printf("\nMultiplication of two values is : %f",r);
r=(*fp[3]) (x,y); // Calling div() function.
printf("\nDivision of two values is : %f",r);
return 0;
}
OUTPUT
Objective
Program to display details of student two (Name, roll no, marks) using structure.
Theory
Structure in c is a user-defined data type that enables us to store the collection of different data
types. Each element of a structure is called a member. Structures simulate the use of classes and
templates as it can store various information
The struct keyword is used to define the structure. Let's see the syntax to define the structure in c.
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
We can declare a variable for the structure so that we can access the member of the structure easily.
There are two ways to declare structure variable:
Program
#include <stdio.h>
struct student {
char name[50];
int roll;
float marks;
} s;
int main() {
printf("Enter information:\n");
printf("Enter name: ");
fgets(s.name, sizeof(s.name), stdin);
printf("Displaying Information:\n");
printf("Name: ");
printf("%s", s.name);
printf("Roll number: %d\n", s.roll);
printf("Marks: %.1f\n", s.marks);
return 0;
}
OUTPUT
Objective
Program to display details of employee using array of structure.
Theory
An array of structures in C can be defined as the collection of multiple structures variables where
each variable contains information about different entities. The array of structures in C are used to
store information about multiple entities of different data types. The array of structures is also
known as the collection of structures.
Program
#include<stdio.h>
struct employee
{
int id,age,salary;
char name[25];
}emp[100];
void main()
{
int i,n;
printf("Enter the no of employees\n");
scanf("%d",&n);
printf("Enter employee info as id , name , age , salary\n");
Department of Computer Science Engineering
Faculty of Engineering
Medi-Caps University
27
for(i=0;i<n;i++)
{
scanf("%d %s %d %d",&emp[i].id,emp[i].name,&emp[i].age,&emp[i].salary);
}
printf("\nEMP_NAME\tEMP_NAME\tEMP_AGE\t\tEMP_SAL\n");
for(i=0;i<n;i++)
{
printf("%d\t\t%s\t\t%d\t\t%d\n",emp[i].id,emp[i].name,emp[i].age,emp[i].salary);
}
}
OUTPUT
Objective
Program to access member of structures using pointers
Theory
The pointers to a structure in C in very similar to the pointer to any in-built data type variable.
struct Employee
{
char name[50];
int age;
float salary;
} employee_one;
struct Employee *employee_ptr;
We can use addressOf operator(&) to get the address of structure variable.
To access a member variable of structure using variable identifier we use dot(.) operator whereas
we use arrow(->) operator to access member variable using structure pointer.
employee_ptr->salary;
Program
#include <stdio.h>
struct employee {
char name[100];
int age;
float salary;
char department[50];
};
int main(){
struct employee employee_one, *ptr;
return 0;
}
OUTPUT
Objective
Program for passing structure to a function
Theory
• A structure can be passed to any function from main function or from any sub function.
• Structure definition will be available within the function only.
• It won’t be available to other functions unless it is passed to those functions by value or by
address(reference).
• Else, we have to declare structure variable as global variable. That means, structure
variable should be declared outside the main function. So, this structure will be visible to
all the functions in a C program.
PASSING STRUCTURE TO FUNCTION IN C:
It can be done in below 3 ways.
• Passing structure to a function by value
• Passing structure to a function by address(reference)
• No need to pass a structure – Declare structure variable as global
Program
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
void display(struct student record);
int main()
{
struct student record;
record.id=1607;
strcpy(record.name, "Shantilal Bhayal");
record.percentage = 86.5;
display(record);
return 0;
}
Department of Computer Science Engineering
Faculty of Engineering
Medi-Caps University
31
void display(struct student record)
{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}
OUTPUT
Objective
Program for returning a structure from a function
Theory
To return a structure from a function the return type should be a structure only.
Returning a struct by value means that a function generates a copy of the entire struct and passes it
back to the caller. This approach is straightforward and effective for small or moderately sized
structs.
Program
#include <stdio.h>
struct student
{
char name[50];
int age;
};
// function prototype
struct student getInformation();
int main()
{
struct student s;
s = getInformation();
printf("\nDisplaying information\n");
printf("Name: %s", s.name);
printf("\nRoll: %d", s.age);
return 0;
}
struct student getInformation()
{
struct student s1;
OUTPUT
Objective
Program to display details of student two (Name, roll no, marks) with the help of union
Theory
A union is a user-defined type similar to structs in C except for one key difference.
Structures allocate enough space to store all their members, whereas unions can only hold one
member value at a time.
How to define a union?
We use the union keyword to define unions. Here's an example:
union car
{
char name[50];
int price;
};
The above code defines a derived type union car.
Create union variables
When a union is defined, it creates a user-defined type. However, no memory is allocated. To
allocate memory for a given union type and work with it, we need to create variables.
Here's how we create union variables.
union car
{
char name[50];
int price;
};
int main()
{
union car car1, car2, *car3;
return 0;
}
Another way of creating union variables is:
union car
{
char name[50];
int price;
} car1, car2, *car3;
In both cases, union variables car1, car2, and a union pointer car3 of union car type are created.
#include <stdio.h>
union student {
char name[50];
int roll;
float marks;
} u;
int main()
{
printf("Enter information:\n");
printf("Enter name: ");
fgets(u.name, sizeof(u.name), stdin);
printf("Displaying Information:\n");
printf("Name: ");
printf("%s", u.name);
printf("Roll number: %d\n", u.roll);
printf("Marks: %.1f\n", u.marks);
return 0;
}
OUTPUT
Objective
To Understand the concept of dynamic memory allocation
Theory
C malloc()
The name "malloc" stands for memory allocation.
The malloc() function reserves a block of memory of the specified number of bytes. And, it
returns a pointer of void which can be casted into pointers of any form.
Syntax of malloc()
ptr = (castType*) malloc(size);
Example
ptr = (float*) malloc(100 * sizeof(float));
The above statement allocates 400 bytes of memory. It's because the size of float is 4 bytes. And,
the pointer ptr holds the address of the first byte in the allocated memory.
The expression results in a NULL pointer if the memory cannot be allocated.
C calloc()
The name "calloc" stands for contiguous allocation.
The malloc() function allocates memory and leaves the memory uninitialized, whereas the calloc()
function allocates memory and initializes all bits to zero.
Syntax of calloc()
ptr = (castType*)calloc(n, size);
Example:
ptr = (float*) calloc(25, sizeof(float));
The above statement allocates contiguous space in memory for 25 elements of type float.
Program
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i, *ptr, sum = 0;
return 0;
}
OUTPUT
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
Objective
Program to allocate memory of array at run time.
Theory
An array is a collection of a fixed number of values. You can't change the size of an array once it's
been declared.It's possible that the size of the Array you declared is insufficient at times. You can
manually set RAM during runtime to remedy this problem. In C programming, we called it
dynamic memory allocation. Malloc(), calloc(), and realloc() are library functions that are used to
allocate memory dynamically.
C malloc() method
In C, the "malloc" or "memory allocation" method is used to allocate a single huge block of
memory with the specified size dynamically. It returns a void pointer that can be cast into any
other type of pointer. Because it does not initialize memory at runtime, each block is initially set
to the default garbage value.
Syntax
ptr = (cast-type*) malloc(byte-size)
For Example:
ptr = (int*) malloc(100 * sizeof(int));
Program
#include <stdio.h>
#include <stdlib.h>
int main() {
int* ptr;
int n, i;
printf("Enter number of elements:");
scanf("%d",&n);
printf("Entered number of elements: %d\n", n);
ptr = (int*)malloc(n * sizeof(int));
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
printf("Memory successfully allocated using malloc.\n");
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
OUTPUT
Objective
To understand the concept of Enum.
Theory
Enum in C
The enum in C is also known as the enumerated type. It is a user-defined data type that consists of
integer values, and it provides meaningful names to these values. The use of enum in C makes the
program easy to understand and maintain. The enum is defined by using the enum keyword.
In the above declaration, we define the enum named as flag containing 'N' integer constants. The
default value of integer_const1 is 0, integer_const2 is 1, and so on. We can also change the default
value of the integer constants at the time of the declaration.
For example:
enum fruits{mango, apple, strawberry, papaya};
The default value of mango is 0, apple is 1, strawberry is 2, and papaya is 3.
Program
Objective
To Understand the concept of Macro
Theory
C macros provide a potent method for code reuse and simplification. They let programmers
construct symbolic names or phrases that are changed to certain values before the compilation
process begins. The use of more macros makes code easier to comprehend, maintain, and makes
mistakes less likely. In this article, we'll delve deeper into the concept of C macros and cover their
advantages, ideal usage scenarios, and potential hazards.
A macro is a segment of code which is replaced by the value of macro. Macro is defined by
#define directive.
There are two types of macros:
• Object-like Macros
• Function-like Macros
Object-like Macros
The object-like macro is an identifier that is replaced by value. It is widely used to represent
numeric constants. For example:
#define PI 3.14
Program
#include<stdio.h>
#define PI 3.14
int main()
{
float r, area;
area = PI * r * r;
return 0;
Department of Computer Science Engineering
Faculty of Engineering
Medi-Caps University
44
}
OUTPUT
Objective
To Understand the concept of macro with argument.
Theory
A simple macro always stands for exactly the same text, each time it is used. Macros can be more
flexible when they accept arguments. Arguments are fragments of code that you supply each time
the macro is used. These fragments are included in the expansion of the macro according to the
directions in the macro definition. A macro that accepts arguments is called a function-like macro
because the syntax for using it looks like a function call.
To define a macro that uses arguments, you write a `#define' directive with a list of argument
names in parentheses after the name of the macro. The argument names may be any valid C
identifiers, separated by commas and optionally whitespace. The open-parenthesis must follow the
macro name immediately, with no space in between.
For example, here is a macro that computes the minimum of two numeric values, as it is defined in
many C programs:
Program
#include<stdio.h>
#include<conio.h>
#define AREA(x) 3.14*x*x
int main()
{
float r1,r2,area;
printf("Enter 1st radius of circle :-");
scanf("%f",&r1);
area=AREA(r1);
printf("Area of circle =%.2f",area);
printf("\nEnter 2st radius of circle :-");
scanf("%f",&r2);
area=AREA(r2);
printf("Area of circle =%.2f",area);
return 0;
}
Objective
Program to create a header file and use it in a program
Theory
The files with .h extension are called header files in C. These header files generally contain
function declarations which we can be used in our main C program, like for e.g. there is need to
include stdio.h in our C program to use function printf() in the program.
Creating myhead.h : Write the below code and then save the file as myhead.h or you can give any
name but the extension should be .h indicating its a header file.
Including the .h file in other program
Program
Myhead.h
Objective
Demonstration of File Operation
Theory
File handing 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.
C File Operations
C file operations refer to the different possible operations that we can perform on a file in C such
as:
1. Creating a new file – fopen() with attributes as “a” or “a+” or “w” or “w+”
2. Opening an existing file – fopen()
3. Reading from file – fscanf() or fgets()
4. Writing to a file – fprintf() or fputs()
5. Moving to a specific location in a file – fseek(), rewind()
6. Closing a file – fclose()
File Pointer in C
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;
File Pointer is used in almost all the file operations in C.
Open a File in C
For opening a file in C, the fopen() function is used with the filename or file path along with the
required access modes.
Syntax of fopen()
FILE* fopen(const char *file_name, const char *access_mode);
Program
#include <stdio.h>
int main(void) {
// creating a FILE variable
FILE *fptr;
// integer variable
int id, score;
Department of Computer Science Engineering
Faculty of Engineering
Medi-Caps University
50
int i, s;
// character variable
char name[255];
char n[255];
// open the file in write mode
fptr = fopen("student", "w");
if (fptr != NULL) {
printf("File created successfully!\n");
}
else {
printf("Failed to create the file.\n");
// exit status for OS that an error occured
return -1;
}
// get student detail
printf("Enter student name: ");
gets(name);
printf("Enter student ID: ");
scanf("%d", &id);
printf("Enter student score: ");
scanf("%d", &score);
return 0;
}
Objective
Program to count number of words, number of character and number of lines from a given text file
Theory
Logic to count characters, words and lines in a file
Step by step descriptive logic to count characters, words and lines in a text file.
if (characters > 0)
{
words++;
lines++;
}
//Display
printf("\nTotal Number of characters: %d", characters);
printf("\nTotal Number of words: %d", words);
printf("\nTotal Number of lines: %d", lines);
fclose(file);
return 0;
}
OUTPUT
Objective
Program in C to delete a specific line from a file
Theory
Then rewind() function is used to set the file position to the beginning of the file of the given
stream. Enter the line number of the line to be deleted using ‘delete_line’ variable.
Then ‘fileptr2’ variable is used to open the new file in write mode. While loop is used to print the
number of characters present in the file. if condition statement is used to copy except the line to be
deleted. The file.Putc() function is used to copy all lines in file replica.c.
Then close the files and rename the file replica.c to original name. Using while loop print the
contents of the file after being modified.
Program
#include <stdio.h>
int main()
{
FILE *fileptr1, *fileptr2;
char filename[40];
char ch;
int delete_line, temp = 1;
printf("Enter file name: ");
scanf("%s", filename);
//open file in read mode
fileptr1 = fopen(filename, "r");
ch = getc(fileptr1);
while (ch != EOF)
{
printf("%c", ch);
ch = getc(fileptr1);
}
//rewind
rewind(fileptr1);
printf(" \n Enter line number of the line to be deleted:");
scanf("%d", &delete_line);
//open new file in write mode
fileptr2 = fopen("replica.c", "w");
ch = getc(fileptr1);
while (ch != EOF)
{
ch = getc(fileptr1);
if (ch == '\n')
OUTPUT
Objective
Write a program in C to copy a file in another name.
Theory
Operations on files
The operations that can be carried out on files in C language are as follows −
Syntax
The syntax for opening and naming file is as follows −
FILE *File pointer;
FILE *fp;
fp = fopen ("sample.txt”, "w”);
With the help of these functions, we can copy the content of one file into another file.
#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *fptr1, *fptr2;
char ch, fname1[20], fname2[20];
fptr1=fopen(fname1, "r");
if(fptr1==NULL)
{
printf(" File does not found or error in opening.!!");
exit(1);
}
printf(" Input the new file name : ");
scanf("%s",fname2);
fptr2=fopen(fname2, "w");
if(fptr2==NULL)
{
printf(" File does not found or error in opening.!!");
fclose(fptr1);
exit(2);
}
while(1)
{
ch=fgetc(fptr1);
if(ch==EOF)
{
break;
}
else
{
fputc(ch, fptr2);
}
}
printf(" The file %s copied successfully in the file %s. \n\n",fname1,fname2);
fclose(fptr1);
fclose(fptr2);
getchar();
}
Objective
Write a program in C to merge two files and write it in a new file
Theory
Merging two files means the content of any two files (entered by user at runtime) gets merged into
the third file in a way that, the content of first source file gets copied to the target file, and then the
content of second source file gets appended to the target file.
Let the given two files be file1.txt and file2.txt.
The following are steps to merge.
1) Open file1.txt and file2.txt in read mode.
2) Open file3.txt in write mode.
3) Run a loop to one-by-one copy characters of file1.txt to file3.txt.
4) Run a loop to one-by-one copy characters of file2.txt to file3.txt.
5) Close all files.
To successfully run the below program file1.txt and fil2.txt must exist in same folder.
Program
#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *fold1, *fold2, *fnew;
char ch, fname1[20], fname2[20], fname3[30];
OUTPUT
Objective
To Understand the concept of encryption.
Theory
Encrypting a file means, we will convert the plaintext (original content of file) to ciphertext. So
that our credential information stored in a file gets converted into ciphertext. Whereas decrypting
a file means getting our content back to original form. To encrypt a file in C programming, you
have to open that file and start reading the file character by character. At the time of reading,
create some algorithm to encrypt the content of the file, and place the content in a temporary file,
character by character. Finally, copy the content of the temporary file to the original file as shown
in the program given below:
Program
#include <stdio.h>
#include <stdlib.h>
void main()
{
char fname[20], ch;
FILE *fpts, *fptt;
fpts=fopen(fname, "r");
if(fpts==NULL)
{
printf(" File does not exists or error in opening..!!");
exit(1);
}
fptt=fopen("temp.txt", "w");
if(fptt==NULL)
{
printf(" Error in creation of file temp.txt ..!!");
fclose(fpts);
exit(2);
}
while(1)
{
Department of Computer Science Engineering
Faculty of Engineering
Medi-Caps University
63
ch=fgetc(fpts);
if(ch==EOF)
{
break;
}
else
{
ch=ch+100;
fputc(ch, fptt);
}
}
fclose(fpts);
fclose(fptt);
fpts=fopen(fname, "w");
if(fpts==NULL)
{
printf(" File does not exists or error in opening..!!");
exit(3);
}
fptt=fopen("temp.txt", "r");
if(fptt==NULL)
{
printf(" File does not exists or error in opening..!!");
fclose(fpts);
exit(4);
}
while(1)
{
ch=fgetc(fptt);
if(ch==EOF)
{
break;
}
else
{
fputc(ch, fpts);
}
}
printf(" File %s successfully encrypted ..!!\n\n", fname);
fclose(fpts);
fclose(fptt);
}
Objective
To Understand the concept of decryption.
Theory
Decryption: Decryption is the process of converting a meaningless message (Ciphertext) into its
original form (Plaintext). It works by applying the conversion algorithm opposite of the one that is
used to encrypt the data. The same key is required to decrypt the information back to its normal
form.
Program
#include <stdio.h>
#include <stdlib.h>
void main()
{
char ch, fname[20];
FILE *fpts, *fptt;
fpts=fopen(fname, "w");
if(fpts==NULL)
{
printf(" File does not exists or error in opening..!!");
exit(1);
}
fptt=fopen("temp.txt", "r");
if(fptt==NULL)
{
printf(" File does not exists or error in opening..!!");
fclose(fpts);
exit(1);
}
while(1)
{
ch=fgetc(fptt);
if(ch==EOF)
{
Department of Computer Science Engineering
Faculty of Engineering
Medi-Caps University
66
break;
}
else
{
ch=ch-100;
fputc(ch, fpts);
}
}
printf(" The file %s decrypted successfully..!!\n\n",fname);
fclose(fpts);
fclose(fptt);
}
OUTPUT
Objective
Write a program in C to remove a file from the disk.
Theory
remove is a function in C programming language that removes a certain file. It is included in the C
standard library header file stdio.h.
Program
#include <stdio.h>
void main()
{
int status;
char fname[20];
printf("\n\n Remove a file from the disk :\n");
printf("----------------------------------\n");
printf(" Input the name of file to delete : ");
scanf("%s",fname);
status=remove(fname);
if(status==0)
{
printf(" The file %s is deleted successfully..!!\n\n",fname);
}
else
{
printf(" Unable to delete file %s\n\n",fname);
}
}
Objective
Write a program to draw a circle and fill blue color in it
Theory
The header file graphics.h contains circle() function which draws a circle with center at (x, y)
and given radius.
Syntax :
circle(x, y, radius);
where, (x, y) is center of the circle. 'radius' is the Radius of the circle.
The header file graphics.h contains setfillstyle() function which sets the current fill pattern and fill
color. floodfill() function is used to fill an enclosed area. Current fill pattern and fill color is used
to fill the area.
Syntax :
Program
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<dos.h>
int main()
{
int gdriver = DETECT,gmode;
initgraph(&gdriver,&gmode,"C:\\TC\\BGI");
setfillstyle(SOLID_FILL,BLUE);
circle(200,200,50);
floodfill(202,202,WHITE);
getch();
}
Objective
Write a program to move a circle using suitable animations
Theory
Program
//moving a circle
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<dos.h>
void main()
{
clrscr();
int gdriver, gmode; //variables declaration
gdriver=DETECT; // detection of graphics driver
int move_location=20; //first location for circle to start
initgraph(&gdriver, &gmode, "c:\\tc\\BGI");
while(!kbhit()) //Checks for currently available keystrokes
{
circle(move_location,210,70);//draws circle
setcolor(BLUE); //sets the color blue of circle
delay(100); //delays of 1/10th of second
cleardevice(); //clears the previous screen/graphics
move_location++;
if(move_location>=600)
{
move_location=0; //repeating the motion.
cleardevice(); //clears the graphics screen
}
}
getch(); //gets one character from user and closes the graphics.
closegraph(); //closes graphics.h
}