0% found this document useful (0 votes)
14 views42 pages

C&ds Unit 2

The document covers advanced features of C programming, focusing on structures, unions, enumerated data types, pointers, file handling, and preprocessor directives. It explains the definition, declaration, initialization, and accessing of structures, as well as the differences between structures and arrays. Additionally, it discusses unions, pointers, and provides example programs demonstrating the use of these concepts in C programming.

Uploaded by

Keerthana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views42 pages

C&ds Unit 2

The document covers advanced features of C programming, focusing on structures, unions, enumerated data types, pointers, file handling, and preprocessor directives. It explains the definition, declaration, initialization, and accessing of structures, as well as the differences between structures and arrays. Additionally, it discusses unions, pointers, and provides example programs demonstrating the use of these concepts in C programming.

Uploaded by

Keerthana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 42

UNIT II NOTES – C PROGRAMMING – ADVANCED FEATURES

Structures – Union – Enumerated Data Types – Pointers: Pointers to Variables, Arrays and
Functions – File Handling – Preprocessor Directives.

STRUCTURE
Explain in detail about the structure with an example. Apr / May 2018 [Nov/Dec 2019]
[Nov/Dec 2020][Apr/May 2021] [NOV/DEC 2022]
What is structure? Create a structure with data members of various types and declare
two structure variables. (Nov/Dec 2014) (Nov/Dec 2015)
Explain in detail the concept and importance of structures with example. (April / May
2017)
Structure Definition
 Structure is a collection of data items of different data types which are grouped together
and each element in a C structure is called member.
 ie., a simple structure contains integer, float & character elements, etc.
(Or)
 A Structure is a collection of different data items that are stored under a common name.
Need for structure data type
Justify the need for structured data type. (Nov/Dec 2014)
 Structure is a group name in which dissimilar data are grouped together.
 Some problem have own memory space, so structure is needed.
 Some problem also has many members that can be accessed at any time without the loss
of the data.

Declaring a Structure
 The structure can be declared with the keyword struct following the name and opening
braces with data elements of different type, then closing brace with semicolon.
Syntax
struct structure_name
{
structure element 1;
structure element 2;
…………………….
…………………….
structure element n;
};
struct structure_name v1,v2……..vn;
Where v1,v2…vn are called as structure variables.
Example
struct book
{
char title[20];
char author[15];
int pages;
float price;
};
struct book b1,b2,b3;
Rules for Declaring a Structure
 A structure must end with a semicolon.
 Usually a structure appears at the top of the source program.
 Each structure element must be terminated.
 The members of the structure can be accessed using the structure variables along with
dot (.) operator.
Accessing Structure Elements
 After declaring the structure type, variables and members, the member of the structure
can be accessed by using the structure variable along with the dot (.) operator.
Example
struct std
{
int no;
char name[15];
int marks;
};
struct std s;
For accessing the structure members from the above example.
s.no; s.name; s.marks;
Where ‘s’ is the structure variable.
Initialization of a Structure
 Like normal variables, the structure variables can also be initialized, but this initialization
can be made at the compile time.
 This initialization can be done in 2 ways.
Example 1
struct
{
int sno;
float avg;
} std = {39, 39.11};
 This assigns the value 39 to std.sno and 39.11 to std.avg. There is a one-to-one
correspondence between the members and their initializing values.
Example 2
struct std
{
int sno;
float avg;
}
main()
{
struct std person1 = {39, 39.11};
struct std person2 = {17, 17.25};
}
 C language does not permit the initialization of individual structure member within the
template. The initialization must be done only in the declaration of the actual variables.
Rules for Initializing Structure
 The individual data members of structure cannot be initialized.
 The structure variables can be initialized at compile time only.
 The order of data members in a structure must match the order of values in enclosed
brackets.
 The uninitialized data members can be initialized by default with zero (0) for int and float,
‘\0’ for character and strings.

Structure within Structure (Structure Assignment / Nested Structure) Apr / May 2018
[Nov/Dec 2021]
 It is possible to assign one structure information to another structure of same type using
simple assignment statement.
User Defined Data types
 C provides a capability that enables the programmer to assign an alternate same to a data
type. This is done with a statement known as typedef.
Syntax
typedef type dataname;
Difference between Array and Structure
Array Structure
 An array is a collection of similar data  Structure is a collection of different
items of same type. data items of different type.
 An array is a derived data type.  It is a user defined data type.
 An array behaves like a built-in data  It must be declared and defined.
type.
Example Program (Accessing Structure Elements)
#include<stdio.h>
#include<conio.h>
struct stud
{
int regno;
char name[10];
int m1;
int m2;
int m3;
};
struct stud s;
void main()
{
float total,avg;
printf("\n Enter the student regno,name,m1,m2,m3:");
scanf("%d%s%d%d%d",&s.regno,&s.name,&s.m1,&s.m2,&s.m3);
total=s.m1+s.m2+s.m3;
avg=total/3;
printf("\n The student Details are:");
printf("\n %d\t%s\t%f\t%f",s.regno,s.name,total,avg);
}
Output:
Enter the student regno, name, m1, m2, m3:
100
Mani
87
98
78
The student Details are:
100 Mani 263.000000 87.666664
Example Program (Student Mark Details using Structure)
Write a C program to create a mark sheet for students using structure. (Dec Jan 2014)
(May/June 2016, Nov / Dec 2016) [NOV/DEC 2022]
Write a C program and algorithm to create mark sheet for students using structure.
Nov / Dec 2017
Write a C program to get 10 student details using structure from the user and display
the details on the screen. Nov 2018 [Nov/Dec 2019]
#include<stdio.h>
#include<conio.h>
struct stud
{
int regno;
char name[10],grade;
int m1,m2,m3;
float avg,tot;
} s[10];
void main()
{
int i,n;
printf("\n Enter the no.of students:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Enter the student regno,name,m1,m2,m3:");
scanf("%d%s%d%d%d",&s[i].regno,&s[i].name,&s[i].m1,&s[i].m2,&s[i].m3);
s[i].tot=s[i].m1+s[i].m2+s[i].m3;
s[i].avg=s[i].tot/3;
if(s[i].m1<35||s[i].m2<35||s[i].m3<35)
s[i].grade='F';
else
{
if(s[i].avg>=75)
s[i].grade='D';
else if(s[i].avg>=60)
s[i].grade='A';
else if(s[i].avg>=50)
s[i].grade='B';
else if(s[i].avg>=35)
s[i].grade='C';
}}
printf("\n STUDENT MARK LIST\n");
printf("\n REGNO\tNAME\tTOTAL\tAvg\tGRADE");
for(i=0;i<n;i++)
printf("\n%d\t%s\t%f\t%f\t%c",s[i].regno,s[i].name,s[i].tot,s[i].avg,s[i].grade);
getch();
}
Output
Enter the no. of students: 02 / 10
Enter the student regno, name, m1, m2, m3: 101
Babu
89
98
78
Enter the student regno, name, m1, m2, m3: 102
Mani
59
68
76
STUDENT MARK LIST
REGNO NAME TOTALAvg GRADE
101 Babu 265.000000 88.333336 D
102 Mani 203.000000 67.666664 A

Example Program (/* Calculate Employee Salary using Structures*/)


Write a C program to store the employee information using structure and search a
particular employee using employee number. (May/June 2014)
Write algorithm and a C program using unions, to prepare the employee pay roll of a
company. Nov / Dec 2017
Illustrate the representation of structures and unions for an employee record having
empid, emp-name, DOB, Basicpay, allowances, deductions with their operations in C.
(Apr/May 2019)
#include<stdio.h>
#include<conio.h>
struct employee {
char name[15];
int empid;
float bsal;
float nsal;
float gross;
};
void main() {
struct employee emp;
float hra,da,tax;
clrscr();
printf("\n Employee Details");
printf("\n Enter the Employee Name:");
scanf("%s",&emp.name);
printf("\n Enter the Employee ID:");
scanf("%d",&emp.empid);
printf("\n Enter the Basic Salary:");
scanf("%f",&emp.bsal);
hra=((10*emp.bsal)/100);
da=((35*emp.bsal)/100);
emp.gross=emp.bsal+hra+da;
emp.net=emp.gross-tax;
printf("\n Employee Name:%s",emp.name);
printf("\n Employee ID:%d",emp.empid);
printf("\n Employee Basic Salary:%f",emp.bsal);
printf("\n HRA:%f",hra);
printf("\n DA:%f",da);
printf("\n Tax:%f",tax);
printf("\n Net Salary:%f",emp.nsal);
printf("\n Gross Salary:%f",emp.gross);
getch();
}
Output:
Employee Details:
Enter the Employee Name: Robin
Enter the Employee ID : 100
Enter the Basic Salary : 30000
Employee Name : Robin
Employee ID : 100
Employee Basic Salary: 30000.000000
HRA : 3000.000000
DA : 10,500.000000
Tax : 4500.000000
Gross Salary : 39000.000000

UNION
Write short notes on union. (Nov/Dec 2014) (Or) What is Union? Discuss with an
example. (April/May 2015) (Nov/Dec 2015, 2016) [Nov/Dec 2020][Apr/May 2021]
 A Union is a collection of different data items that are stored under a common name. Here
same memory is shared by its members.
 It is a derived data type and it is declared like structure.
 In structure each member has its own storage location, whereas all the members of union
use the same location.

Syntax
union union_name
{
union member 1;
union member 2;
…………………..
union member n;
};
union union_variable;
Example
union result
{
int mark;
float avg;
char grade;

};
union result s;
Example Program using Union
#include<stdio.h>
#include<conio.h>
union stud {
int a;
char b[2];
};
void main()
{
union stud c;
c.a=256;
printf("\nc.a value is %d",c.a);
printf("\nc.b[0] value is %d",c.b[0]);
printf("\nc.b[1] value is%d",c.b[1]);
}
Output:
c.a value is 256
c.b[0] value is 0
c.b[1] value is 1

Program using Structure and Union


#include<stdio.h>
#include<conio.h>
struct student
{
int a;
int b;
char c;
}s;
union student1
{
int a;
int b;
char c;
}s1;
void main()
{
printf("\n The size of structure is %d",sizeof(s));
printf("\n The size of union is %d",sizeof(s1));
getch();
}
Output:
The size of structure is 5
The size of union is 2
Example Program
/*Student Marks using Union*/
#include<stdio.h>
main()
{
union student
{
char name[20];
char regno[12];
int avg;
char grade;
}
stud[25],*ptr;
int i,no;
printf(“Enter the Number of the Students:”);
scanf(“%d”,&no);
for(i=0;i<no;i++)
{
printf(“\n Student [%d] Information:\n”,i+1);
printf(“Enter the Name:”);
scanf(“%s”,stud[i].name);
printf(“\n Enter the Roll No of the Student:”);
scanf(“%s”,stud[i].regno);
printf(“\n Enter the Average Value of the Student:”);
scanf(“%d”,&stud[i].avg);
}
pt=stud;
for(pt=stud;pt<stud+no;ptr++)
{
if(ptr->avg<30)
ptr->grade=’D’;
else if(ptr->avg<50)
ptr->grade=’C’;
else if(ptr->avg<70)
ptr->grade=’B’;
else
ptr->grade=’A’;
}
printf(“\n”);
printf(“NAME REGISTER-NO AVERAGE GRADE\n”);
for(ptr=stud;ptr<stud+no;pt++)
{
printf(“%-20s%-10s”,ptr->name,ptr->regno); printf(“%10d \t %c\n”,ptr->avg,ptr->grade);
}
}Output:
Enter the Number of the Students… 3
Student [1] Information:
Enter the Name: Jack
Enter the Roll No of the Student: 31705205001
Enter the Average Value of the Student: 90
Student [2] Information:
Enter the Name: Raj
Enter the Roll No of the Student: 31705205002
Enter the Average Value of the Student: 88
Student [3] Information:
Enter the Name: Kiran
Enter the Roll No of the Student: 31705205003
Enter the Average Value of the Student: 75
NAME REGISTER-NO AVERAGE GRADE
Jack 31705205001 90 S
Raj 31705205002 88 A
Kiran 31705205003 75 B
Difference between Data types, Structure and Union [Nov/Dec 2020][Apr/May 2021]
Data types Structure Union
 char: The most  Structure is a collection of  Structure is a collection of
basic data type in different data items of different data items of
C. It stores a single different type stored different type.
character and under a common name.  It is a derived data type.
requires a single  It is a user defined data  In union, all the members
byte of memory in type. have a common storage
almost all  In structure, each location.
compilers. member has its own  Members cannot be
 int: As the name storage location. accessed at the same
suggests, an int  Members can be accessed time.
variable is used to at the same time.
store an integer.
 float: It is used to
store decimal
numbers (numbers
with floating point
value) with single
precision.

POINTERS
Discuss in detail about pointer with an example. (Or) Explain in detail the concept of
pointer in C language. (April / May 2017)
 Pointer is a variable which contains the memory address of another variable. (Or) A
pointer is a variable whose value is the address of another variable.
 The memory address is the location where program instructions and data are stored;
pointers can be used to access and manipulate data stored in the memory.
Example
a=10
a Variable
10 Value
80F Address
 The variable that holds memory address is called pointer variables.
 A pointer variable is therefore nothing but a variable that contains an address, which is a
location of another variable.
 Value of pointer variable will be stored in another memory location.

Features of Pointers
 It is more efficient in handling array and structure.
 It is used for saving memory space.
 It reduces the length and complexity of the program.
 It provides dynamic memory allocation.
Advantages of Pointers
 It is more compact and efficient code.
 It is used to achieve clarity and simplicity.
 It enables us to access the memory directly.
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int x=5;
printf("\n The Address of x = %u",&x);
printf("\n The Value of x = %d",x);
}
Output
The Address of x = 8714
The Value of x = 5
Declaring a Pointer Variable
 Pointer is a variable that contains the address of another variable.
Syntax: data_type *pointer-name;
Eg: int *a;
 Initialization of Pointer Variable (Accessing the Pointer Variable)
 Pointer Initialization is the process of assigning address of a variable to pointer variable.
 Pointer variable contains address of variable of same data type.
 In C language address operator (&) is used to determine the address of a variable.
 The ampersand (&) returns the address of the variable associated with it.
int a = 10 ;
int *ptr ; // Pointer Declaration
ptr = &a ; // Pointer Initialization
(Or)
int *ptr = &a ; // Initialization and Declaration Together
 The ampersand (&) is an operator, which is used to access the address of a variable and
assign it to a pointer to initialize it.
Dereferencing of Pointer
 Once a pointer has been assigned the address of a variable. To access the value of
variable, pointer is dereferenced, using the indirection operator (*).

Example Program 1
#include<stdio.h>
#include<conio.h>
void main()
{
int x=5;
int *a;
a=&x;
printf("\n The Value of x = %d",x);
printf("\n The Address of x = %u",&x);
printf("\n The Value of a = %d",a);
printf("\n The Value of x = %d",*a);
}
Output
The Value of x = 5
The Address of x = 8758
The Value of a = 8758
The Value of x = 5
Example Program 2
#include<stdio.h>
#include<conio.h>
void main()
{
int y=10;
int *a;
a=&y;
printf("\n The Value of y = %d",y);
printf("\n The Address of y = %u",&y);
printf("\n The Value of a = %d",a);
printf("\n The Address of a = %u",&a);
}
Output
The Value of y = 10
The Address of y = 5001
The Value of a = 5001
The Address of a = 8000
Null Pointer
 A pointer is said to be null pointer if zero is assigned to the pointer.
Example
int *a,*b;
a=b=0;
Pointer to Pointer
Here one pointer stores the address of another pointer variable.
Example:
int x=10,*a,**b;
a=&x;
b=&a;

Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10;
int *b,**c;
b=&a;
c=&b;
printf("\n The Value of a = %d",a);
printf("\n The Address of a = %u",&a);
printf("\n The Value of b = %d",b);
printf("\n The Address of b = %u",&b);
printf("\n The Value of c = %d",c);
printf("\n The Address of c = %u",&c);
}
Output
The Value of a = 10
The Address of a = 5001
The Value of b = 5001
The Address of b = 8000
The Value of c = 8000
The Address of c = 9000

POINTERS ARITHMETIC
Explain in detail about pointers arithmetic with suitable example.
 A pointer in C is an address, which is a numeric value. Therefore we can perform
arithmetic operations on a pointer as we do on a numeric value.
 The arithmetic operations on pointer variable affect the memory address pointed by
pointer.
The different types of arithmetic operations performed on pointers are,
 Incrementing Pointer
 Decrementing Pointer
 Pointer Addition
 Pointer Subtraction
 Pointer Comparison
Incrementing Pointer
 Incrementing a pointer to an integer data will cause its value to be incremented by 2.
 This differs from compiler to compiler as memory required to store integer vary compiler
to compiler
 Incrementing Pointer Variable Depends Upon data type of the Pointer variable.
Syntax:
new_value = current_address + i * sizeof(pointer_data type)

Data Older Address Next Address stored in pointer


Type stored in pointer after incrementing (ptr++)

int 1000 1002

float 1000 1004

char 1000 1001


Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3] = {10,20,30};
int i, *ptr;
clrscr();
ptr = a;
for(i=0; i<3; i++)
{
printf("\n Address=%x",ptr);
printf("\t Value=%d",*ptr);
ptr++;
}
getch();
}
Output:
Address = fff0 Value=10
Address = fff2 Value=20
Address = fff4 Value=30

Decrementing Pointer
 Decrementing a pointer to an integer data will cause its value to be decremented by 2.
 This differs from compiler to compiler as memory required to store integer vary compiler
to compiler.
 Decrementing of pointer variable depends upon data type of the pointer variable.
Syntax:
new_address = current_address - i * sizeof(pointer_data type)

Older Address Next Address stored in


Data
stored in pointer after incrementing
Type
pointer (ptr–)

int 1000 0998

float 1000 0996

char 1000 0999


Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3] = {10,20,30};
int i, *ptr;
clrscr();
ptr = &a[2];
for(i=3; i>0; i--)
{
printf("\n Address=%x",ptr);
printf("\t Value=%d",*ptr);
ptr--;
}
getch();
}

Output:
Address = fff4 Value=30
Address = fff2 Value=20
Address = fff0 Value=10
Pointer Addition
 In C Programming we can add any integer number to Pointer variable. It is perfectly legal
in c programming to add integer to pointer variable.
Syntax:
final_value = (address) + (number * sizeof(pointer_data type))
Consider the following example,
int *ptr , n;
ptr = &n ;
ptr = ptr + 3;
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a = 5, b = 10;
int *x, *y;
clrscr();
x = &a, y = &b;
printf(“%d”, (*x + *y));
getch();
}
Output:
15
Pointer Subtraction
 In C Programming we can subtract any integer number to Pointer variable. It is perfectly
legal in c programming to add integer to pointer variable.
Syntax:
ptr = initial_address - n * (sizeof(pointer_data_type))
For Example,
int *ptr , n;
ptr = &n ;
ptr = ptr - 3;
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a = 5, b = 10;
int *x, *y;
clrscr();
x = &a, y = &b;
printf(“%d”, (*x - *y));
getch();
}
Output: -5
Pointer Comparison [NOV/DEC 2022]
 Pointer comparison is valid only if the two pointers are pointing to same array.
 All Relational Operators can be used for comparing pointers of same type.
 All Equality and Inequality Operators can be used with all Pointer types.
 Pointers cannot be Divided or Multiplied.
Example
#include<stdio.h>
int main()
{
int *ptr1;
float *ptr2;
ptr1 = (int *) 1000;
ptr2 = (float *) 2000;
if(ptr2 > ptr1)
printf("ptr2 is far from ptr1");
return(0);
}
Output:
ptr2 is far from ptr1
Array and Pointer
Explain in detail about Array and Pointer with an example. Nov / Dec 2016, Apr / May
2018
 Arrays are closely related to pointers in C programming 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.
Eg: int a[5]={1,2,3,4,5};
Memory a[0] a[1] a[2] a[3] a[4]
Address
Value 1 2 3 4 5
Base Address 4000 4002 4004 4006 4008
Explanation
 a[5] means the array ‘a’ has 5 elements and of integer data type.
 The base address (Assume 4000) of the array starts with 0th element of the array.
 The array is in integer type, the integer will have 2 bytes and hence the address of the
next address element is incremented by 2.
Example
#include<stdio.h>
int main()
{
char c[4];
int i;
for(i=0;i<4;++i)
{
printf("Address of c[%d]=%x\n",i,&c[i]);
}
return 0;
}
Output:
Address of c[0]=28ff44
Address of c[1]=28ff45
Address of c[2]=28ff46
Address of c[3]=28ff47
Relation between Arrays and Pointers
int num[5];

 In arrays, name of the array always points to the first element of an array.
 Here, address of first element of an array is &num[0].
 Also, num represents the address of the pointer where it is pointing. Hence, &num[0] is
equivalent to arr.
 Also, value inside the address &num[0] and address num are equal. Value in address
&num[0] is num[0] and value in address num is *num.
 Hence, num[0] is equivalent to *arr.
Similarly,
&a[1] is equivalent to (a+1) AND, a[1] is equivalent to *(a+1).
&a[2] is equivalent to (a+2) AND, a[2] is equivalent to *(a+2).
&a[3] is equivalent to (a+1) AND, a[3] is equivalent to *(a+3).
.
.
&a[i] is equivalent to (a+i) AND, a[i] is equivalent to *(a+i).
Example
// Program to find the sum of six numbers with arrays and pointers.
#include<stdio.h>
int main()
{
int i,class[6],sum=0;
printf("Enter 6 Numbers:\n");
for(i=0;i<6;++i)
{
scanf("%d",(class+i)); // (class+i) is equivalent to &class[i]
sum += *(class+i); // *(class+i) is equivalent to class[i]
}
printf("Sum=%d",sum);
return 0;
}

Output:
Enter 6 Numbers:
2
3
4
5
3
4
Sum=21
Example of Pointer and Functions
/* C Program to swap two numbers using pointers and function. */
#include <stdio.h>
void swap(int *a,int *b);
int main()
{
int num1=5,num2=10;
swap(&num1,&num2); /* address of num1 and num2 is passed to swap function */
printf("Number 1 = %d\n",num1);
printf("Number 2 = %d",num2);
return 0;
}
void swap(int *a,int *b) /* pointer a and b points to address of num1 and num2 respectively */
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
Output:
Number 1 = 10
Number 2 = 5
Explanation
 The address of memory location num1 and num2 are passed to function and the pointers
*a and *b accept those values.
 So, the pointer a and b points to address of num1 and num2 respectively.
 When, the values of pointer are changed, the value in memory location also changed
correspondingly.
 Hence, change made to *a and *b was reflected in num1 and num2 in main function.
Pointers with Multi-Dimensional Array
 A multidimensional array can also be represented with an equivalent pointer notation.
Syntax
data-type (*pointer variable) [Expression2];
Example
int (*a)[20]; //Pointer
int a[10][20]; //Array
Example Program
#include<stdio.h>
main()
{
int arr[3][2] = {
{5, 100},
{10, 101},
{15, 102},
};
int a, b;
for(a=0;a<3;a++)
{
printf(“address of %d array=%u”,a,&arr[a]);
for(b=0;b<2;b++)
printf(“value =%d”,arr[a][b]);
}
}
Output
Address of 0 Array=4000
Value=5
Value=100
Address of 1 Array=4002
Value=10
Value=101
Address of 2 Array=4000
Value=15
Value=102
Pointers and Strings
Character and Pointer
 A character pointer is a pointer to the character.
 It can be declared as,
char *pointer_character;
String and Pointer
char *pointers message;

FILES:[APR/MAY 2022]

INTRODUCTION TO FILES:
 A file is a collection of related data that a computers treats as a single unit.
 A File is a collection of data stored in the secondary memory.
 C uses a structure called FILE (defined in stdio.h) to store the attributes of a file.
 Files are not only used for storing the data, programs are also stored in files.

How is a file stored?


– Stored as sequence of bytes, logically contiguous.
(may not be physically contiguous on disk).
Why files are needed?
 When a program is terminated, the entire data is lost.
 Storing in a file will preserve your data even if the program terminates.
 If you have to enter a large number of data, it will take a lot of time to enter them all.
 However, if you have a file containing all the data, you can easily access the contents of
the file using few commands in C.
 You can easily move your data from one computer to another without any changes.
Types of Files
 There are two types of files.
 Text :contains ASCII codes only
 Binary :can contain non-ASCII characters
Image, audio, video, executable, etc.

FILE HANDLING (or) BASIC FILE OPERATIONS [APR/MAY 2022]


Explain in detail various operations that can be done on file giving suitable examples.
[APR/MAY 2019][Apr/May2021][Nov/Dec2020]
Discuss about the modes of file handling. [NOV/DEC 2019]
1. Declare a file pointer variable.
2. fopen - open a file- specify how its opened (read/write) and type (binary/text).
3. fclose - close an opened file
4. fread - read from a file
5. fwrite - write to a file
6. fseek/fsetpos - move a file pointer to somewhere in a file.
7. ftell/fgetpos - tell you where the file pointer is located.

1..Declaration of file pointer


 A pointer variable is used to points a structure FILE.
 The members of the FILE structure are used by the program in various file access
operation, but programmers do not need to concerned about them.

FILE *file_pointer_name;
Eg : FILE *fp

2. Open a file using the fopen() function. [NOV/DEC 2022]


 The file open function (fopen) serves two purposes:
 It makes the connection between the physical file and the stream.
 It creates “a program file structure to store the information” C needs to process the
file.
 To open a file using the fopen() function.
 Its syntax is,
FILE *fopen(const char *fname,const char* mode);

3.Close the file using the fclose() and fflush() functions.


 Closing and Flushing Files
 The file must be closed using the fclose() function. Its prototype is ,
Syntax int fclose(FILE *fp);

Example programs
Program to check whether the file exist or not */
void main()
{
FILE *fp;
char *x;
clrscr();
printf("\n enter the file name : ");
gets(x);
fp=fopen(x,"r");
if(fp==NULL)
{
printf("The file ---%s--- is not found in the present directory",x);
}
else
{
printf("The file ---%s--- is found in the present directory",x);
}
fclose(fp);
getch();
}
Reading and Writing Files
Exapmle :
#include <stdio.h>
int main ( )
{
FILE *outfile, *infile ;
int b = 5, f ;
float a = 13.72, c = 6.68, e, g ;
outfile = fopen ("testdata", "w") ;
fprintf (outfile, “ %f %d %f ", a, b, c) ;
fclose (outfile) ;
infile = fopen ("testdata", "r") ;
fscanf (infile,"%f %d %f", &e, &f, &g) ;
printf (“ %f %d %f \n ", a, b, c) ;
printf (“ %f %d %f \n ", e, f, g) ;

fread ()
syntax:
size_t fread(void *ptr, size_t size, size_t n, FILE *stream);

 fread reads a specified number of equal-sized


 data items from an input stream into a block.
ptr = Points to a block into which data is read
size = Length of each item read, in bytes
n = Number of items read
stream = file pointer

Example:
#include <stdio.h>
int main()
{
FILE *f;
char buffer[11];
if (f = fopen("fred.txt", “r”))
{
fread(buffer, 1, 10, f);
buffer[10] = 0;
fclose(f);
printf("first 10 characters of the file:\n%s\n", buffer);
}
return 0;
}

fwrite()
Syntax: size_t fwrite(const void *ptr, size_t size, size_t n, FILE*stream);

 fwrite appends a specified number of equal-sized data items to an output file.


ptr = Pointer to any object; the data written begins at ptr
size = Length of each item of data
n =Number of data items to be appended
stream = file pointer

Example:

#include <stdio.h>
int main()
{
char a[10]={'1','2','3','4','5','6','7','8','9','a'};
FILE *fs;
fs=fopen("Project.txt","w");
fwrite(a,1,10,fs);
fclose(fs);
return 0;
}

Character input / output:

 Two functions are used to read the character from the file and write it into
another file.
 These functions are getc() & putc() functions. Its prototype is,
int getc(FILE *file_pointer);
putc( char const_char, FILE *file_pointer);

Detecting the end of a file:


 When reading from a text-mode file character by character, one can look for the end-of-file
character.
 The symbolic constant EOF is defined in stdio.h as -1, a value never used by a real
character.

Eg: while((c=getc(fp)!=EOF).

Examples:
/* Read a string into a text file */
void main()
{
FILE *fp;
char text[80];
int i;
clrscr();
fp=fopen("Sample.txt","w");
printf("\n Enter the text : ");
gets(text);
for(i=0;i<strlen(text);i++) // Read a stream of charcters
putc(text[i],fp);
if(fp!=NULL)
printf("\n The string copied into a text file ");
fclose(fp);
getch();
}

Working with Text files :


 C provides various functions to working with text files.
 Four functions can be used to read text files and four functions that can be used to write
text files into a disk. These are,
 fscanf() & fprintf()
 fgets() & fputs()
 fgetc() & fputc()
 fread() & fwrite()

 The prototypes of the above functions are,

1. int fscanf(FILE *stream, const char *format,list);


2. int getc(FILE *stream);
3. char *fgets(char *str,int n,FILE *fp);
4. int fread(void *str,size_t size,size_t num, FILE *stream);
5. int fprintf(FILE *stream, const char *format,list);
6. int fputc(int c, FILE *stream);
7. int fputs(const char *str,FILE *stream);
8. int fwrite(const void *str,size_t size, size_t count,FILE *stream);

fprintf()

Syntax:
fprintf (fp,"string",variables);
Example:
int i = 12;
float x = 2.356;
char ch = 's';
FILE *fp;
fp=fopen(“out.txt”,”w”);
fprintf (fp, "%d %f %c", i, x, ch);

fscanf()
Syntax:
fscanf (fp,"string",identifiers);
Example:
FILE *fp;
Fp=fopen(“input.txt”,”r”);
int i;
fscanf (fp,“%d",i);

getc()

Syntax:
identifier = getc (file pointer);

Example:
FILE *fp;
fp=fopen(“input.txt”,”r”);
char ch;
ch = getc (fp);
putc()
 write a single character to the output file, pointed to by fp.
Example:
FILE *fp;
char ch;
putc (ch,fp);

End of file
 There are a number of ways to test for the end-of-file condition.
 Another way is to use the value returned by the fscanf function:

Exaple:
FILE *fptr1;
int istatus ;
istatus = fscanf (fptr1, "%d", &var) ;
if ( istatus == feof(fptr1) )
{
printf ("End-of-file encountered.\n”) ;
}

fseek()
 This function sets the file position indicator for the stream pointed to by stream or you can
say it seeks a specified place within a file and modify it.
SEEK_SET Seeks from beginning of file
SEEK_CUR Seeks from current position
SEEK_END Seeks from end of file

Example:

#include <stdio.h>
int main()
{
FILE * f;
f = fopen("myfile.txt", "w");
fputs("Hello World", f);
fseek(f, 6, SEEK_SET); SEEK_CUR, SEEK_END
fputs(" India", f);
fclose(f);
return 0;
}

ftell()
syntax:
offset = ftell( file pointer );

 "ftell" returns the current position for input or output on the file
Example:
#include <stdio.h>
int main(void)
{
FILE *stream;
stream = fopen("MYFILE.TXT", "w");
fprintf(stream, "This is a test");
printf("The file pointer is at byte %ld\n", ftell(stream));
fclose(stream);
return 0;
}

Example programs on text files:

/* Read a string into a text file using fputs() function */


void main()
{
FILE *fp;
char text[80];
int i;
clrscr();
fp=fopen("Sample.txt","w");
printf("\n Enter the text : ");
gets(text);
fputs(text,fp); //write a string into a file
if(fp!=NULL)
printf("\n The string copied into a text file ");
fclose(fp);
getch();
}

/* Program to copy from one file to another file */ [Nov/Dec2021]


void main()
{
FILE *fp,*fp1;
int ch;
clrscr();
fp=fopen("ex_file4.c","r");
fp1=fopen("ex_file2.c","w");
if(fp==NULL)
printf(“File is not available”);
ch=getc(fp);
while(ch!=EOF)
{
putc(ch,fp1);
ch=getc(fp);
}
fclose(fp);
fclose(fp1);
getch(); }

/* Program to display the content of the file */


void main()
{
FILE *fp;
int ch;
clrscr();
fp=fopen("ex_file4.c","r");
if(fp==NULL)
printf(“File is not available”);
ch=getc(fp);
while(ch!=EOF)
{
printf("%c",ch);
ch=getc(fp);
}
fclose(fp);
getch();
}

/* read and write the content of the file using fprintf() and fscanf() functions */
[NOV/DEC 2022]
void main()
{
FILE *fptr;
char name[20];
int age;
float salary;
clrscr();
/* open for writing */
fptr = fopen("abc.txt", "w");
if (fptr == NULL)
{
printf("File does not exists \n");
return;
}
printf("Enter the name \n");
scanf("%s", name);
fprintf(fptr, "Name = %s\n", name);
printf("Enter the age\n");
scanf("%d", &age);
fprintf(fptr, "Age = %d\n", age);
printf("Enter the salary\n");
scanf("%f", &salary);
fprintf(fptr, "Salary = %f\n", salary);
getch();
fclose(fptr);
}

PREPROCESSOR DIRECTIVES
Discuss about the preprocessor directives in C. (Or) Write short notes on #include,
#endif statement. (Nov/Dec 2014) [Nov/Dec 2020][Apr/May 2021]
Write short notes on #include, #ifndef, #endif statements. (Nov/Dec 2015)
Describe about the preprocessors with suitable example. (May/June 2016), Nov / Dec
2016
 Before a C program is compiled in a compiler, source code is processed by a program
called preprocessor. This process is called preprocessing.
 Commands used in preprocessor are called preprocessor directives and they begin with
“#” symbol.
Rules for Defining Preprocessor
 Every preprocessor must start with # symbol.
 The preprocessor is always placed before main() function.
 The preprocessor cannot have termination with semicolon.
 There is no assignment operator in #define statement.
 A program in C language involves into different processes. Below diagram will help you to
understand all the processes that a C program comes across.
Below is the list of preprocessor directives that C language offers.
1. File Inclusion
2. Macro Substitution
3. Conditional Inclusion
1. File Inclusion
 This is used to include an external file, which contains functions or some other macro
definitions to our source program.
Syntax
#include”Filename” and #include<Filename>
 Where Filename is the name of the file that can be included in our source program.
 When ‘filename’ is quoted, it searches for that file in current directory and then in
standard directories.
 When ‘filename’ is included in the angle brackets (< >), the included file is searched only
in the standard directory.
Example
#include<stdio.h>
#include”loop.c”
Where “stdio.h” is the file that contains standard I/O function in ‘C’ standard directory and
“loop.c” is the program written by the user.
Example Program
#include<stdio.h>
#include<conio.h>
#include "addition.txt"
void main()
{
int a,b;
printf("\n Enter the Numbers:");
scanf("%d%d",&a,&b);
printf("The Value is %d",add(a,b));
getch();
}
addition.txt
int add(int a,int b)
{
return(a+b);
}
Output:
Enter the Numbers:
7
4
The Value is 11
2. Macro Substitutions [NOV/DEC 2022]
 This is used to define symbolic constants in the source program. The identifier or string or
integer defined is replaced by macro substitution.
ie., It is used to define and use integer, string, or identifier in the source program.
There are three types of macros.
 Simple Macros
 Augmented Macros
 Nested Macros
(i). Simple Macros
 It is commonly used to define symbolic constants
Syntax
# define identifier string/integer
Eg:
#define A 10
#define pi 3.14
#define CITY “chennai”
Example Program
#include<stdio.h>
#include<conio.h>
#define pi 3.14
#define CITY "chennai"
void main()
{
printf("The Value is %f",2*pi);
printf("\n The Value CITY is %s",CITY);
getch();
}
Output:
The Value is 6.280000
The Value CITY is Chennai
(ii). Augmented Macros
 It is used to define more complex forms in the source program.
Syntax
#define identifier (v1,v2,….) string/integer
Eg:
#define cube(n) (n*n*n)
Example Program
#include<stdio.h>
#include<conio.h>
#define cube(n) (n*n*n)
void main()
{
printf("\n The Value of 3 cube is %d",cube(3));
getch();
}
Output:
The Value of 3 cube is 27
(iii). Nested Macro
 Here one macro is used by another macro.
Eg:
#define a 3
#define sq a*a
Example Program
#include<stdio.h>
#include<conio.h>
#define a 3
#define sq a*a
void main()
{
printf("\n The Value is %d",sq);
getch();
}
Output:
The Value is 9
3. Conditional Inclusion
 These are used to control the preprocessor with conditional statements.
The preprocessor directives are,
#if, #elif (else if) – It allows only constant expression. #elif establishes an if-else-if chain
for multiple compilation options.
#define – Used to define symbolic constant.
#ifdef – It is used to check the identifier was defined as a macro name.
#ifndef - It is used to check the identifier was not defined as a macro name.
#else – It allows only constant expression. If the result of the expression is TRUE, then
block of statement between #if and #endif is followed. If the result of the expression is
FALSE, then block of statement between #if and #endif is skipped.
#undef – Used to undefine a macro.
Example Program
#include<stdio.h>
#include<conio.h>
#define a 3
#ifdef a
#define c a+5
#endif
void main()
{
printf("\n The value C is %d",c);
getch();
}
Output: The value C is 8

UNIT II TWO MARKS – C PROGRAMMING – ADVANCED FEATURES


Structures – Union – Enumerated Data Types – Pointers: Pointers to Variables, Arrays and
Functions – File Handling – Preprocessor Directives.

1) Define Structure. What is a Structure? (Or) What do you mean by structure?


(May/June, Nov / Dec 2016, 2017)
 Structure is a collection of data items of different data types which are grouped
together and each element in a C structure is called member.
(Or)
 A Structure is a collection of different data items that are stored under a common
name.

2) How will you declare a structure?


 The structure can be declared with the keyword struct following the name and
opening braces with data elements of different type, then closing brace with
semicolon.
Syntax
struct structure_name
{
structure element 1;
structure element 2;
…………………….
…………………….
structure element n;
};
struct structure_name v1,v2……..vn;
Where v1,v2…vn are called as structure variables.

3) Write the rules for declaring a structure.


 A structure must end with a semicolon.
 Usually a structure appears at the top of the source program.
 Each structure element must be terminated.
 The members of the structure can be accessed using the structure variables along
with dot (.) operator.

4) How will you access the elements of a structure?


 After declaring the structure type, variables and members, the member of the
structure can be accessed by using the structure variable along with the dot (.)
operator.
Syntax: Structure_variable_name.member_name
Example
struct std
{
int no;
char name[15];
int marks;
};
struct std s;
For accessing the structure members from the above example.
s.no; s.name; s.marks;
Where ‘s’ is the structure variable.

5) Write the rules for initialization of a structure.


 The individual data members of structure cannot be initialized.
 The structure variables can be initialized at compile time only.
 The order of data members in a structure must match the order of values in
enclosed brackets.
 The uninitialized data members can be initialized by default with zero (0) for int and
float, ‘\0’ for character and strings.

6) What is Nested Structure?


 It is a process of assigning one structure information into another structure of same
type using simple assignment statement.

7) What are the advantages of using array? Apr / May 2018


1. It is used to represent multiple data items of same type by using only single
name.
2. It can be used to implement other data structures like linked lists, stacks, queues,
trees, graphs etc.
3. 2D arrays are used to represent matrices.

8) Compare array with structure. (Or) Differentiate between array and structure.
(Dec/Jan 2014)
Array Structure
 An array is a collection of similar data  Structure is a collection of
items of same type. different data items of different
 An array is a derived data type. type.
 An array behaves like a built-in data  It is a user defined data type.
type.  It must be declared and defined.
9) Define Union. (Or) What is Union? (Or) What is the purpose of unions in C?
(May/June 2014) (Or) State the importance of union. (May/June 2016) [Nov/Dec
2020][Apr/May 2021]
 A Union is a collection of different data items that are stored under a common
name. Here same memory is shared by its members.
 It is a derived data type and it is declared like structure.
 In structure each member has its own storage location, whereas all the members of
union use the same location.

10) How will you declare a union?


Syntax
union union_name
{
union member 1;
union member 2;
…………………..
union member n;
};
union union_variable;

11) Difference between Structure and Union. Nov 2018


Structure Union
 Structure is a collection of different  Structure is a collection of
data items of different type stored different data items of different
under a common name. type.
 It is a user defined data type.  It is a derived data
 In structure, each member has its own type.
storage location.  In union, all the members have
 Members can be accessed at the a common storage location.
same time.  Members cannot be accessed
at the same time.
12) What is a Storage Class? (Or) What are Storage Classes? (April / May, Nov / Dec
2017)
 A storage class defines the scope (visibility) and life time of variables and/or
functions within a C program.

What are the various types of storage classes in C? (Or) What are the storage
13) classes available in C? (April / May 2017)
There are following storage classes which can be used in a C program.
 auto
 register
 static
 extern

14) What is Pointer? (Or) Define Pointer. (Or) What is the use of Pointers? (or)
Define a pointer and initialize it. (Apr/May 2019) (Jan 2014), Nov / Dec 2016
 Pointer is a variable which contains the memory address of another variable.
 The memory address is the location where program instructions and data are
stored; pointers can be used to access and manipulate data stored in the memory.
 It is always denoted by ‘*’ operator.
 Pointer initialization int *a,b;
a=&b;
15) Write down the features of pointer. What are the advantages of using pointers
in a program? Nov / Dec 2017
 It is efficient in handling data.
 It is used for saving memory space.
 It reduces the length and complexity of the program.
 It provides dynamic memory allocation.
 Two dimensional and multidimensional array representations are easy in pointers.

16) What are the advantages of pointer?


 It is more compact and efficient code.
 It is used to achieve clarity and simplicity.
 It enables us to access the memory directly.

17) How will you declare a pointer? How pointer variable is initialized? Apr / May
2018
 Pointer is a variable that contains the address of another variable.
Syntax: data_type *pointer-name;
Eg: int *a;

18) What is & and * operator?


& - Address operator
* - Indirection Operator / Dereferencing Operator

19) What is Dereferencing Pointer?


 Dereferencing Operation is performed to access or manipulate data contained in
memory location pointed to by a pointer.
 Any Operation performed on the de-referenced pointer directly affects the value of
variable it points to.
20) What is indirection operator?
 Asterisk (*) indirection operator is used along with pointer variable while
dereferencing the pointer variable.
 Asterisk operator is also called as value at operator.
 When used with pointer variable, it refers to variable being pointed to; this is called
as Dereferencing of Pointers.

21) What is the difference between the indirection and address operators? (Or)
What is an address operator and indirection operator? (Nov / Dec 2014) (Nov /
Dec 2015)
 The indirection operator (*) returns the value of the variable stored in a pointer.
 The address operator (&) returns the memory address of the variable.

22) What does null pointer mean?


 A pointer is said to be a null pointer when its right side value is 0.
 A null pointer can never point to a valid data. For checking a pointer, if it is
assigned to 0, then it is a null pointer and is not valid.

23) What is a Character Pointer?


 A character pointer can also be used to access character arrays and string
constants in the same way as accessing numeric arrays using their respective
pointer variable.
Syntax: char *pointer_character;

24) Define Array of Pointers.


 Array notation is a form of relative addressing.
 The compiler treats the subscripts as a relative offset from the beginning of the
array.
 When a pointer variable is set to the start of an array and is incremented to find the
next element, absolute addressing is being implemented.
25) What is Pointer to Pointer?
 Here one pointer stores the address of another pointer variable.
Example:
int x=10,*a,**b;
a=&x;
b=&a;
26) How is pointer arithmetic done? (May/June 2016)
 Pointers arithmetic is done by adding, subtracting, comparing, incrementing and
decrementing the values assigned to the pointer variables.

27) What are the different types of arithmetic operations performed on pointers?
(or)
List some of pointer manipulations allowed in C language. [Nov/Dec 2021]
 Incrementing Pointer
 Decrementing Pointer
 Pointer Addition
 Pointer Subtraction
 Pointer Comparison

28) What is Dynamic Memory Allocation? (April / May 2017)


 The process of allocating memory at runtime is known as dynamic memory
allocation.
 Library routines known as "memory management functions" are used for allocating
and freeing memory during execution of a program.
 These functions are defined in stdlib.h.

29) What are the various dynamic memory allocation functions? (April / May 2017)
 malloc() - Used to allocate blocks of memory in required size of bytes.
 free() - Used to release previously allocated memory space.
 calloc() - Used to allocate memory space for an array of elements.
 realloac() - Used to modify the size of the previously allocated memory space.

30) Write short notes on Tower of Hanoi.


 The tower of Hanoi is a children’s playing game, played with three poles and a
number of different sized disks, each has a hole in center.
 The objective of this game is to transfer the disks from the left most pole to the
right most pole, without ever placing a larger disk on the top of the smaller disk.
 Only one disk may be moved at a time and each disk must always be placed around
one of the poles.

31) What is Preprocessor Directive? (Or) What is the use of preprocessor directives?
(May/June 2014) (Or) Define Pre-processor directives in C and list out few
examples. (April / May 2015, 2018) Nov 2018 (Apr/May 2019)
 Before a C program is compiled in a compiler, source code is processed by a
program called preprocessor. This process is called preprocessing.
 Commands used in preprocessor are called preprocessor directives and they begin
with “#” symbol.

32) What are the rules for defining preprocessor directive?


 Every preprocessor must start with # symbol.
 The preprocessor is always placed before main() function.
 The preprocessor cannot have termination with semicolon.
 There is no assignment operator in #define statement.

33) What are different types of preprocessor directives in C? (Or) Write any two
preprocessor directive in C. (Dec/Jan 2014) Nov 2018 (Apr/May 2019)
The different types of preprocessor directives in C language are,
 File Inclusion
 Macro Substitution
 Conditional Inclusion

34) Define File Inclusion. [Nov/Dec 2019]


 This is used to include an external file, which contains functions or some other
macro definitions to our source program.
Syntax
#include”Filename” and #include<Filename>
Where Filename is the name of the file that can be included in our source program.
Example
#include<stdio.h> - compiler searches in the standard library.
#include”loop.c” – Compiler searches in the current directory.

35) What is Macro Substitution?


 This is used to define symbolic constants in the source program. The identifier or
string or integer defined is replaced by macro substitution.
 ie., It is used to define and use integer, string, or identifier in the source program.

36) What are the different types of macro substitution?


There are three types of macros. They are,
 Simple Macros
 Argumented Macros
 Nested Macros

37) What is Simple Macros?


 It is commonly used to define symbolic constants
Syntax
# define identifier string/integer
Eg:
#define A 10
#define pi 3.14
#define CITY “chennai”

38) What is Argumented Macros?


 It is used to define more complex forms in the source program.
Syntax
#define identifier (v1,v2,….) string/integer
Eg:
#define cube(n) (n*n*n)
39) What is Conditional Inclusion? [NOV/DEC 2022]
What is the use of #define preprocessor? (Nov/Dec 2014) (Nov / Dec 2015)
These are used to control the preprocessor with conditional statements.
The preprocessor directives are,
#define – Used to define symbolic constant.
#ifdef – Used to test macro condition.
#else – Used to specify alternative in #ifdef.
#undef – Used to undefine a macro.
40) Define file.
 A file is a collection of related data that a computers treats as a single unit.
 A File is a collection of data stored in the secondary memory.
 C uses a structure called FILE (defined in stdio.h) to store the attributes of a file.
 Files are not only used for storing the data, programs are also stored in files.

41) How is a file stored?


– Stored as sequence of bytes, logically contiguous.
(may not be physically contiguous on disk).
42) Why files are needed? [APR/MAY 2019]
 When a program is terminated, the entire data is lost.
 Storing in a file will preserve your data even if the program terminates.
 If you have to enter a large number of data, it will take a lot of time to enter them all.
 However, if you have a file containing all the data, you can easily access the contents of
the file using few commands in C.
 You can easily move your data from one computer to another without any changes.

43) What are two main ways a file can be organized? [NOV/DEC 2019]
 Sequential file organization
 Indexed file organization

42) Write the types of Files.


 There are two types of files.
 Text :contains ASCII codes only
 Binary :can contain non-ASCII characters
Image, audio, video, executable, etc.

43) Write the modes of file handling or file operations. [NOV/DEC 2019]
 Declare a file pointer variable.
 fopen - open a file- specify how its opened (read/write) and type (binary/text).
 fclose - close an opened file
 fread - read from a file
 fwrite - write to a file
 fseek/fsetpos - move a file pointer to somewhere in a file.
 ftell/fgetpos - tell you where the file pointer is located.

44) What is declaration of file pointer?


 A pointer variable is used to points a structure FILE.
 The members of the FILE structure are used by the program in various file access
operation, but programmers do not need to concerned about them.

FILE *file_pointer_name;
Eg : FILE *fp

45) What is Open a file using the fopen() function? [Nov/Dec2021]


 The file open function (fopen) serves two purposes:
 It makes the connection between the physical file and the stream.
 It creates “a program file structure to store the information” C needs to process the
file.
 To open a file using the fopen() function.
 Its syntax is,
FILE *fopen(const char *fname,const char* mode);

46) List down the modes of fopen.


47) Write about Close the file using the fclose() and fflush() functions.
 Closing and Flushing Files
 The file must be closed using the fclose() function. Its prototype is ,
Syntax int fclose(FILE *fp);

48) Write the syntax for fscanf.


fread ()
syntax:
size_t fread(void *ptr, size_t size, size_t n, FILE *stream);

 fread reads a specified number of equal-sized


 data items from an input stream into a block.
ptr = Points to a block into which data is read
size = Length of each item read, in bytes
n = Number of items read
stream = file pointer

49) Describe fwrite().


fwrite()
Syntax: size_t fwrite(const void *ptr, size_t size, size_t n, FILE*stream);

 fwrite appends a specified number of equal-sized data items to an output file.


ptr = Pointer to any object; the data written begins at ptr
size = Length of each item of data
n =Number of data items to be appended
stream = file pointer

Example:

#include <stdio.h>
int main()
{
char a[10]={'1','2','3','4','5','6','7','8','9','a'};
FILE *fs;
fs=fopen("Project.txt","w");
fwrite(a,1,10,fs);
fclose(fs);
return 0;
}

50) What is Character input / output?


 Two functions are used to read the character from the file and write it into
another file.
 These functions are getc() & putc() functions. Its prototype is,
int getc(FILE *file_pointer);
putc( char const_char, FILE *file_pointer);

51) How to detecting the end of a file?[Apr/May2021][Nov/Dec2020]


 When reading from a text-mode file character by character, one can look for the end-of-file
character.
 The symbolic constant EOF is defined in stdio.h as -1, a value never used by a real
character.

Eg: while((c=getc(fp)!=EOF).

52) Write a c program to read a string to text file. [Nov/Dec2021]


/* Read a string into a text file */
void main()
{
FILE *fp;
char text[80];
int i;
clrscr();
fp=fopen("Sample.txt","w");
printf("\n Enter the text : ");
gets(text);
for(i=0;i<strlen(text);i++) // Read a stream of charcters
putc(text[i],fp);
if(fp!=NULL)
printf("\n The string copied into a text file ");
fclose(fp);
getch();
}

53) Write syntax for fprintf().


fprintf()

Syntax:
fprintf (fp,"string",variables);
Example:
int i = 12;
float x = 2.356;
char ch = 's';
FILE *fp;
fp=fopen(“out.txt”,”w”);
fprintf (fp, "%d %f %c", i, x, ch);
fscanf()
Syntax:
fscanf (fp,"string",identifiers);
Example:
FILE *fp;
Fp=fopen(“input.txt”,”r”);
int i;
fscanf (fp,“%d",i);

getc()

Syntax:
identifier = getc (file pointer);

54) What is end of file?


End of file
 There are a number of ways to test for the end-of-file condition.
 Another way is to use the value returned by the fscanf function:

Exaple:
FILE *fptr1;
int istatus ;
istatus = fscanf (fptr1, "%d", &var) ;
if ( istatus == feof(fptr1) )
{
printf ("End-of-file encountered.\n”) ;
}

55) Define fseek().


fseek()
 This function sets the file position indicator for the stream pointed to by stream or you can
say it seeks a specified place within a file and modify it.
SEEK_SET Seeks from beginning of file
SEEK_CUR Seeks from current position
SEEK_END Seeks from end of file

56) What is ftell()?


syntax:
offset = ftell( file pointer );

 "ftell" returns the current position for input or output on the file

57) List the types of file processing.

 Sequential access
 Random access

58) Describe sequential access file


 In computer science, sequential access means that a group of elements (such as data in
a memory array or a disk file or on magnetic tape data storage) is accessed in a
predetermined, ordered sequence.
 Example: JIO
 Sequential access is sometimes the only way of accessing the data, for example if it is on a
tape.
 It may also be the access method of choice, for example if all that is wanted is to process a
sequence of data elements in order.[1]
 In spatial dimension, request size, distance, backward accesses, re-accesses can affect
sequentially.
 For temporal sequentially, characteristics such as multi-stream and inter-arrival time
threshold has impact on the definition of sequentially.
 In data structures, a data structure is said to have sequential access if one can only visit
the values it contains in one particular order.
 The canonical example is the linked list.
 Indexing into a list that has sequential access requires O(n) time, where n is the index.
 As a result, many algorithms such as quick sort and binary search degenerate into bad
algorithms that are even less efficient than their naive alternatives; these algorithms are
impractical without random access.
 On the other hand, some algorithms, typically those that do not have index, require only
sequential access, such as merge sort, and face no penalty.

59) Describe random access file.


 Individual records of a random-access file are normally fixed in length and may be
accessed directly (and thus quickly) without searching through other records.
 Example: face book

60) Write the function used in Random Access To File.


There is no need to read each record sequentially, if we want to access a particular
record. C supports these functions for random access file processing.
 fseek()
 ftell()
 rewind()
61) Write about ftell().
This function returns the value of the current pointer position in the file.The value is count
from the beginning of the file.
Syntax: ftell(fptr);
Where fptr is a file pointer.

62) Write about rewind()


This function is used to move the file pointer to the beginning of the given file.
Syntax: rewind( fptr);
Where fptr is a file pointer.
Example program for fseek():

63) What is the difference between sequential access and random access files.
[Nov/Dec2020][Apr/May2021]
Difference between Sequential and Random Access Files
 When we are talking about sequential or random access to data files we refer to the
way data is written or read from a file on a computer system.
 Sequential Access to a data file means that the computer system reads or writes
information to the file sequentially, starting from the beginning of the file and
proceeding step by step.
 On the other hand, Random Access to a file means that the computer system can read
or write information anywhere in the data file. This type of operation is also called
“Direct Access” because the computer system knows where the data is stored (using
Indexing) and hence goes “directly” and reads the data.
 Sequential access has advantages when you access information in the same order all
the time. Also is faster than random access.
 On the other hand, random access file has the advantage that you can search through it
and find the data you need more easily (using indexing for example). Random Access
Memory (RAM) in computers works like that.

42) Can you subtract pointers from each other? State the reason. [Nov/Dec 2020]
[Apr/May 2021]
In C Programming we can subtract any integer number to Pointer variable. It is
perfectly legal in c programming to add integer to pointer variable.
Syntax:
ptr = initial_address - n * (sizeof(pointer_data_type))
For Example,
int *ptr , n;
ptr = &n ;
ptr = ptr - 3;
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a = 5, b = 10;
int *x, *y;
clrscr();
x = &a, y = &b;
printf(“%d”, (*x - *y));
getch();
}
43.What is enumerated data types? [NOV/DEC 2022]
Enumeration or Enum in C is a special kind of data type defined by the user. It
consists of constant integrals or integers that are given names by a user. The use of enum
in C to name the integer values makes the entire program easy to learn, understand, and
maintain by the same or even different programmer.

You might also like