Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

UNIT - 5

STRUCTURE & UNION

Data Types

C programming language which has the ability to divide the data into different types.
The type of a variable determine the what kind of values it may take on. The various
data types are.

• Simple Data type

• Integer, Real, Void, Char

• Structured Data type

• Array, Strings

• User Defined Data type

• Enum, Structures, Unions

Structure Data Type

A structure is a user defined data type that groups logically related data items of
different data types into a single unit. All the elements of a structure are stored at
contiguous memory locations. A variable of structure type can store multiple data items of
different data types under the one name. As the data of employee in company that is name,
Employee ID, salary, address, phone number is stored in structure data type.

Defining of Structure

A structure has to defined, before it can used. The syntax of defining a structure is

struct <struct_name>

<data_type> <variable_name>;

<data_type> <variable_name>;

……..
<data_type> <variable_name>;

};

Example of Structure

The structure of Employee is declared as

struct employee
{
int emp_id;

char name[20];

float salary;

char address[50];

int dept_no;

int age;

};
Memory Space Allocation

Declaring a Structure Variable

A structure has to declared, after the body of structure has defined. The syntax of

declaring a structure is

Struct <struct_name>
<variable_name>;

The example to declare the variable for defined structure “employee”


struct employee e1;

Here e1 variable contains 6 members that are defined in structure.

Initializinga Structure Members

The members of individual structure variable is initialize one by one or in a single statement.

The example to initialize a structure variable is

1) Struct employee e1 = {1,“Hemant”,12000, “3 vikas colony new delhi”,10, 35);

2) e1.emp_id=1;

e1.dept_no=1;

e1.name=“Hemant”;

e1.age=35;

e1.salary=12000;

e1.address=“ LPU JALANDHAR”;

Accessing a Structure Members

The structure members cannot be directly accessed in the expression. They are accessed by

using the name of structure variable followed by a dot and then the name of member variable.

The method used to access the structure variables are e1.emp_id, e1.name, e1.salary,

e1.address, e1.dept_no, e1.age. The data with in the structure is stored and printed by this

method using scanf and printf statement in c program.

Structure Assignment

The value of one structure variable is assigned to another variable of same type using
assignment statement. If the e1 and e2 are structure variables of type employee then the
statement
e1 = e2;

assign value of structure variable e2 to e1. The value of each member of e2 is assigned to
corresponding members of e1.

Program to implement the Structure

#include<stdio.h>

#include<conio.h>

struct employee

int emp_id;

char name[20];

float salary;

char address[50];

int dept_no;

int age;

};

void main ( )

{ struct employee e1, e2;

printf (“Enter the employee id of employee”);

scanf(“%d”,&e1.emp_id);

printf (“Enter the name of employee”);

scanf(“%s”,e1.name);

printf (“Enter the salary of employee”);

scanf(“%f”,&e1.salary);

printf (“Enter the address of employee”);


scanf(“%s”,e1.address);

printf (“Enter the department of employee”);

scanf(“%d”,&e1.dept_no);

printf (“Enter the age of employee”);

scanf(“%d”,&e1.age);

printf (“Enter the employee id of employee”);

scanf(“%d”,&e2.emp_id);

printf (“Enter the name of employee”);

scanf(“%s”,e2.name);

printf (“Enter the salary of employee”);

scanf(“%f”,&e2.salary);

printf (“Enter the address of employee”);

scanf(“%s”,e2.address);

printf (“Enter the department of employee”);

scanf(“%d”,&e2.dept_no);

printf (“Enter the age of employee”);

scanf(“%d”,&e2.age);

printf (“The employee id of employee is : %d”, e1.emp_id);

printf (“The name of employee is : %s”, e1.name);

printf (“The salary of employee is : %f”, e1.salary);

printf (“The address of employee is : %s”, e1.address);

printf (“The department of employee is : %d”, e1.dept_no);

printf (“The age of employee is : %d”, e1.age);


printf (“The employee id of employee is : %d”,

e2.emp_id);

printf (“The name of employee is : %s”,

e2.name);

printf (“The salary of employee is : %f”,

e2.salary);

printf (“The address of employee is : %s”,

e2.address);

printf (“The department of employee is : %d”,

e2.dept_no);

printf (“The age of employee is : %d”,e2.age);

getch();

Output of Program

Enter the employee id of employee 1


Enter the name of employee Rahul
Enter the salary of employee 15000
Enter the address of employee 4,villa area, Delhi
Enter the department of employee 3
Enter the age of employee 35
Enter the employee id of employee 2
Enter the name of employee Rajeev
Enter the salary of employee 14500
Enter the address of employee flat 56H, Mumbai
Enter the department of employee 5
Enter the age of employee 30

The employee id of employee is : 1


The name of employee is : Rahul
The salary of employee is : 15000
The address of employee is : 4, villa area, Delhi
The department of employee is : 3
The age of employee is : 35
The employee id of employee is : 2
The name of employee is : Rajeev
The salary of employee is : 14500
The address of employee is : flat 56H, Mumbai
The department of employee is : 5
The age of employee is : 30

Array of Structure

C language allows to create an array of variables of structure. The array of structure


is used to store the large number of similar records. For example to store the record
of 100 employees then array of structure is used. The method to define and access
the array element of array of structure is similar to other array. The syntax to define
the array of structure is

Program to implement the Array of Structure

#include <stdio.h>
#include <conio.h>
struct employee
{
int emp_id;
char name[20];
float salary;
char address[50];
int dept_no;
int age;
};

void main ( )
{
struct employee e1[5];
int i;
for (i=1; i<=100; i++)
{
printf (“Enter the employee id of employee”);
scanf (“%d”,&e[i].emp_id);
printf (“Enter the name of employee”);
scanf (“%s”,e[i].name);
printf (“Enter the salary of employee”);
scanf (“%f”,&e[i].salary);

printf (“Enter the address of employee”);


scanf (“%s”, e[i].address);
printf (“Enter the department of employee”);
scanf (“%d”,&e[i].dept_no);
printf (“Enter the age of employee”);
scanf (“%d”,&e[i].age);
}
for (i=1; i<=100; i++)
{
printf (“The employee id of employee is : %d”,
e[i].emp_id);
printf (“The name of employee is: %s”,e[i].name);

printf (“The salary of employee is: %f”,


e[i].salary);
printf (“The address of employee is : %s”,
e[i].address);
printf (“The department of employee is : %d”,
e[i].dept_no);
printf (“The age of employee is : %d”, e[i].age);
}
getch();
}

Structures within Structures

C language define a variable of structure type as a member of other structure type.


The syntax to define the structure within structure is
struct <struct_name>
{
<data_type> <variable_name>;
struct <struct_name>
{ <data_type>

<variable_name>;
……..}<struct_variable>;
<data_type> <variable_name>; }
Example of Structure within Structure

The structure of Employee is declared as

struct employee
{
int emp_id;
char name[20];
float salary;
int dept_no;
struct date
{ int day;
int month;
int year;
}doj;
};

Accessing Structures within Structures

The data member of structure within structure


is accessed by using two period (.) symbol.
The syntax to access the structure within
structure is
struct _var. nested_struct_var. struct_member;
For Example:-
e1.doj.day;
e1.doj.month;
e1.doj.year;

Pointers and Structures

C language can define a pointer variable of structure type. The pointer variable to
structure variable is declared by using same syntax to define a pointer variable of
data type. The syntax to define the pointer to structure
struct <struct_name> *<pointer_var_name>;

For Example:
struct employee *emp;
It declare a pointer variable “emp” of employee type.

Access the Pointer in Structures

The member of structure variable is accessed by using the pointer variable with
arrow operator(->) instead of period operator(.). The syntax to access the
pointer to structure.
pointer_var_name->structure_member;

For Example:

Emp->name;
Here “name” structure member is accessed through pointer variable emp.

Passing Structure to Function

The structure variable can be passed to a function as a parameter. The program to


pass a structure variable to a function.
#include <stdio.h>
#include <conio.h>
struct employee
{
int emp_id;
char name[20];
float salary;
};

void main ( )
{
struct employee e1;
printf (“Enter the employee id of employee”);
scanf(“%d”,&e1.emp_id);
printf (“Enter the name of employee”);
scanf(“%s”,e1.name);
printf (“Enter the salary of employee”);
scanf(“%f”,&e1.salary);
printdata (struct employee e1);
getch();
}
void printdata( struct employee emp)
{
printf (“\nThe employee id of employee is : %d”, emp.emp_id);
printf (“\nThe name of employee is : %s”, emp.name);
printf (“\nThe salary of employee is : %f”, emp.salary);
}

Function Returning Structure

The function can return a variable of structure type like a integer and float variable. The
program to return a structure from function.
#include <stdio.h>
#include <conio.h>
struct employee
{
int emp_id;
char name[20];
float salary;
};

void main ( )
{
struct employee emp;
emp=getdata();
printf (“\nThe employee id of employee is : %d”, emp.emp_id);
printf (“\nThe name of employee is : %s”, emp.name);
printf (“\nThe salary of employee is : %f”, emp.salary);
getch();
}

struct employee getdata( )


{
struct employee e1;
printf (“Enter the employee id of employee”);
scanf(“%d”,&e1.emp_id);
printf (“Enter the name of employee”);
scanf(“%s”,e1.name);
printf (“Enter the salary of employee”);
scanf(“%f”,&e1.salary);
return(e1);
}

Union Data Type

A union is a user defined data type like structure. The

union groups logically related variables into a single unit. The union data type allocate
the space equal to space need to hold the largest data member of union. The union allows
different types of variable to share same space in memory. There is no other difference
between structure and union than internal difference. The method to declare, use and
access the union is same as structure.

Defining of Union

A union has to defined, before it can used. The syntax of


defining a union is

union <union_name>
{
<data_type> <variable_name>;
<data_type> <variable_name>;
……..
<data_type> <variable_name>;
};

Example of Union

The union of Employee is declared as


union employee
{
int emp_id;
char name[20];
float salary;
char address[50];
int dept_no;
int age;
};

Difference between Structures & Union

1) The memory occupied by structure variable is the sum of sizes of all the members
but memory occupied by union variable is equal to space hold by the largest data member
of a union.
2) In the structure all the members are accessed at any point of time but in union only
one of union member can be accessed at any given time.

Application of Structures
Structure is used in database management to maintain data about books in library,
items in store, employees in an organization, financial accounting transaction in
company. Beside that other application are
1) Changing the size of cursor.
2) Clearing the contents of screen.
3) Drawing any graphics shape on screen.
4) Receiving the key from the keyboard.
5) Placing cursor at defined position on screen.
6) Checking the memory size of the computer.
7) Finding out the list of equipments attach to computer.
8) Hiding a file from the directory.
9) Sending the output to printer.
10) Interacting with the mouse.
11) Formatting a floppy.
12) Displaying the directory of a disk.

Storage Class in C

Introduction
Storage class explain the behavior of the variable in terms of scope and lifetime, it also
determine the initial of the variable.
Scope of the variable is the region over which the variable is visible or valid.
Life time of the variable is the time during which memory is associated with the variable.
Initial value is the value assigned to the variable implicitly if no value is assigned to it by the
programmer.
There are four types of storage class available in C:
 Auto
 Extern
 Static
 Register
AUTO

All local variables has this storage class. Default value is the
garbage value.
Scope of the variable is only between the blocks where it is declared.
Lifetime is till the control remains within the block or function where these variables are
defined.
These variables are destroyed whenever block ends or function jump occur.
To declare auto storage class auto keyword is used.
Example:
 auto int n;
Auto keyword is optional all the local variables by default fall under this storage class.
Example:
 int n;

Extern
Scope is through out the program. Lifetime is till the end of the
program. Initial value is 0.
Extern keyword is used to declare the variable of this storage class.
 extern int x;
By default global variable has this storage class.
STATIC

It is special case of local variable.


These are defined inside the function or block.
Its scope is inside the block or the function where it is defined.
Initial value is 0.
Its value is retained between different function calls.
Lifetime is same as the global variable i.e. through out the program.
Keyword static is used to define this type of variable.
REGISTER
Register variable behave in every way same as the auto variable. The only difference is that
register variable are store inside the computer register instead of the memory. They are used
when CPU has to access the variable very frequently. Eg looping variable.
They are defined by placing keyword register before the datatype of variable.
Example
 register int A=10;

C Pre-processor
 Six phases to execute C:
1. Edit
2. Preprocess
3. Compile
4. Link
5. Load
6. Execute

C Preprocessor
 All preprocessor directives begin with #
 Possible actions
 Inclusion of other files
 Definition of symbolic constants & macros
 Conditional compilation of program code
 Conditional compilation of preprocessor directives

Preprocessor Directives
 #define for symbolic constants
 #define identifier text
 Creates symbolic constants
 The “identifier” is replaced by “text” in the program

Example
#define PI 3.14
area = PI * radius * radius;

 Replaced by “area = 3.14 * radius * radius” by preprocessor before compilation


Conditional Compilation

 Controls the execution of preprocessor directives & compilation of code


 Define NULL, if it hasn’t been defined yet

#if !defined(NULL)
#define NULL 0
#endif

 Use to comment out code (for comments)

#if 0
code prevented from compiling
#endif
FILE HANDLING
What is a File?
● A file is a collection of related data that a
computers treats as a single unit.
● Computers store files to secondary storage so
that the contents of files remain intact when a
computer shuts down.
● When a computer reads a file, it copies the file
from the storage device to memory; when it
writes to a file, it transfers data from memory to
the storage device.
● C uses a structure called FILE (defined in
stdio.h) to store the attributes of a file.
Steps in Processing a File

1. Create the stream via a pointe2. Open the file, associating the stream name with the file
name. Create the stream via a pointer variable using the FILE structure:
FILE *p;
2. Open the file, associating the stream name with the file
name.
3. Read or write the data.
4. Close the file.
The basic file operations are
● 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.
File Open Modes
More on File Open Modes

Additionally,
● r+ - open for reading and writing, start at beginning
● w+ - open for reading and writing (overwrite file)
● a+ - open for reading and writing (append if file exists)

File Open
● 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.
● Syntax:
filepointer=fopen(“filename”, “mode”);

More On fopen
● The file mode tells C how the program will use the file.
● The filename indicates the system name and location for the file.
● We assign the return value of fopen to our pointer variable:
spData = fopen(“MYFILE.TXT”, “w”);
spData = fopen(“A:\\MYFILE.TXT”, “w”);

More On fopen

Closing a File
● When we finish with a mode, we need to close the file before ending the program or
beginning another mode with that same file.
● To close a file, we use fclose and the pointer variable:
fclose(spData);

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);

fgetc()

Syntax:
identifier = fgetc (file pointer);
Example:
FILE *fp;
fp=fopen(“input.txt”,”r”);
char ch;
ch = fgetc (fp);

fputc()

write a single character to the output file, pointed to by fp.


Example:
FILE *fp;
char ch;
fputc (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:
FILE *fptr1;
int istatus ;
istatus = fscanf (fptr1, "%d", &var) ;
if ( istatus == feof(fptr1) )
{
printf ("End-of-file encountered.\n”) ;
}

Reading and Writing Files

#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) ;
}

Example

#include <stdio.h>
#include<conio.h>
int main()
{
char ch;
FILE *fp;
fp=fopen("out.txt","r");
while(!feof(fp))
{
ch=getc(fp);
printf("\n%c",ch);
}
fcloseall( );
}

fread ()

Declaration:
size_t fread(void *ptr, size_t size, size_t n, FILE *stream);
Remarks:
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()

Declaration:
size_t fwrite(const void *ptr, size_t size, size_t n, FILE*stream);
Remarks:
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;
}

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.
Seeks from beginning
SEEK_SET
of file
Seeks from current
SEEK_CUR
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()

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;
}
Questions

Part-A

1. Distinguish between arrays and structures.


Arrays Structures
a. An array is a collection of data items of a. A structure is a collection of data items
same data type. Arrays can only be of different data types. Structures can be
declared. declared and defined.
b. There is no keyword for arrays b. The keyword for structures is struct.
c. An array name represents the address of c. A structure name is known as tag. It is a
the starting element Shorthand notation of the declaration.
d. An array cannot have bit fields d. A structure may contain bit fields

1. Differentiate structures and union.


Structure Union
a. Every member has its own memory. a. All members use the same memory.
b. The keyword used is struct. b. The keyword used is union.
c. All members occupy separate memory c. Different interpretations for the same
location, hence different interpretations of memory location are possible.
the same memory location are not possible.
d. Consumes more space compared to union. d. Conservation of memory is possible.

2. Define Structure in C.
Structure can be defined as a collection of different data types which are grouped
together and each element in a C structure is called member. To access structure
members in C, structure variable should be declared. The keyword used is struct.

3. How will you define a structure?


A structure can be defined as

struct tag
{
datatype member 1;
datatype member 2;
………
………
datatype member n;
};
where struct is a keyword, tag is a name that identifies structures, member 1,
member 2,….. member n are individual member declarations.

4. How will you declare structure variables?


Declaration of structure variables includes the following

statements
a. The keyword struct
b. The structure name
c. List of variable names separated by commas
d. Terminating semicolon
struct library_books
{
char title[20]; char author[15]; int pages;
float price;
};
struct library_books b1,b2,b3;

5. What is meant by Union in C? (May 2014)


A union is a special data type available in C that enables to store different data types
in the same memory location. Union can be defined with many members, but only
one member can contain a value at any given time. Unions provide an efficient way
of using the same memory location for multi-purpose.

How to define a union in C

The format of the union statement is as follows

union tag
{

member definition;

member definition;

....

Member definition;

} one or more union variables

6. How can you access the member of union?


To access any member of a union, use the member access operator (.). The member access
operator is coded as a period between the union variable name and the union member
to access. Union keyword is used to define variables of union type.

7. List the features of structures. (May 2015)


The features of structures are as follows
a. All the elements of a structure are stored at contiguous memory locations
b. A variable of structure type can store multiple data items of different data
types under the one name

8. List the main aspects of working with structure.

a. Defining a structure type (Creating a new type).


b. Declaring variables and constants (objects) of the newly created type.
c. Initializing structure elements

9. What are the two ways of passing a structure to function in C?

a. Passing structure to a function by value


b. Passing structure to a function by address(reference)

10. Write any two advantage of Structure.

a. It is used to store different data types.


b. Each element can be accessed individually.

11. How to initialize a structure variable? Give it’s syntax.


Static storage class is used to initialize structure. It should being and end with curly braces.
Syntax: Static structure tag-field structure variable = {value1, value2,...value 3};

12. Define Anonymous structure.


Unnamed anonymous structure can be defined as the structure definition that does
not contain a structure name. Thus the variables of unnamed structure should be
declared only at the time of structure definition.

13. What are the operations on structures?


The operations on structures are
a. Aggregate operations: An aggregate operation treats an operand as an
entity and operates on the entire operand as whole instead of operating on
its constituent members.
b. Segregate operations: A segregate operation operates on the individual
members of a structure object.

14. How to access members of a structure object?

a. Direct member access operator (dot operator)


b. Indirect member access operator(arrow operator)

15. What is the use of ‘period (.)’ in C?


To access any member of a structure, we use the member access operator (.). The
member access operator is coded as a period between the structure variable name
and the structure member that we wish to access. Period is used to initialize
structure. The members of structure can be accessed individually using period
operator. Ex: S1.roll.no;

16. How will you access the structures member through pointers?
The structures member can be accessed through pointers by the following ways
a. Referencing pointer to another address to access memory
b. Using dynamic memory allocation

17. Define Nested structure.


Nested structure can be defined as the structure within structure. One structure can
be declared inside other structure as we declare structure members inside a
structure. The structure variables can be a normal structure variable or a pointer
variable to access the data.

18. Define array of structures.


Each elements of an array represent a structure variable. If we want to store more
array objects in a structure, then we can declare “array of structure”.

19. What are the pre-processor directives? (Jan 2014, May 2014, 2015)
Preprocessor directives are the commands used in preprocessor and they begin with
“#” symbol. Before a C program is compiled in a compiler, source code is processed
by a program called preprocessor. This process is called preprocessing.
Syntax: #define
Macro
This macro defines constant value and can be any of the basic data types.
Syntax: #include <file_name>
Header file
The source code of the file “file_name” is included in the main program at
inclusion
the specified place.
Syntax: #ifdef, #endif, #if, #else, #ifndef
Conditional
Set of commands are included or excluded in source program before
compilation
compilation with respect to the condition.
Syntax: #undef, #pragma
Unconditional
#undef is used to undefine a defined macro variable. #Pragma is used to call
compilation
a function before and after main function in a C program.

20. What are storage classes?


A storage class is the one that defines the scope (visibility) and life time of variables and/or
functions within a C Program.

21. What are the storage classes available in C?


Storage classes are categorized in four types as,
Automatic Storage
Class - auto
Register Storage
Class - register
Static Storage
Class - static
External Storage
Class - extern

22. What is register storage in storage class?


Register is used to define local variables that should be stored in a register instead of RAM.
This means that the variable has a maximum size equal to the register size (usually one word)
and can‟t have the unary '&' operator applied to it (as it does not have a memory location). Ex.
register int a=200;
23. What is static storage class? (Nov 2014)
Static is the default storage class for global variables. The static storage class
object will be stored in the main memory.
Ex. static int Count=19;

24. Define Auto storage class in C.


Auto is the default storage class for all local variables. The auto storage class data
object will be stored in the main memory. These objects will have automatic
(local) lifetime.
Ex. auto int Month;

25. Define Macro in C. What is the use of #define preprocessor? (Nov 2014)
A macro can be defined as the facility provided by the C preprocessor by which a
token can be replaced by the user defined sequence of characters. Macros are defined
with the help of define directive. Its format is: #define identifier replacement.
#define TABLE_SIZE 100

26. What are conditional Inclusions in Preprocessor Directive?


The conditional inclusion directives are the one that is used to control the
preprocessor with conditional statements. Ex: #ifdef, #else, #endif

27. What you meant by Source file Inclusion in Preprocessor directive?


When the preprocessor finds an #include directive it replaces it by the entire
content of the specified file. There are two ways to specify a file to be included:
#include "filename.extension
" #include
<filename.extension>

28. Define Compilation process.


Compilation process is defined as the processing of source code files and the creation of an
object' file. The compiler produces the machine language instructions that correspond to the
source code file that was compiled.

29. What is a file?


A file is a collection of related data stored on a secondary storage device like
hard disk. Every file contains data that is organized in hierarchy as fields,
records, and databases. Stored as sequence of bytes logically contiguous (may
not be physically contiguous on disk).

30. List out the type of files.


The following are the
types of files
a. Text file or ASCII text file: collection of information or
data which are easily readable by humans. Ex. .txt, .doc,
.ppt, .c, .cpp
b. Binary file: It is collection of bytes. Very tough to read by humans. Ex. .gif,
.bmp,
.jpeg, .exe, .obj

31. What are the standard streams available?


The standards streams available in C language are
a. Standards input(stdin)
b. Standards output(stdout)
c. Standards error(stderr)

32. What are file attributes?

a. File name
b. File Position
c. File Structure
d. File Access Methods
e. Attributes flag

33. What is the use of functions fseek(), fread(), fwrite() and ftell()?
a. fseek(f,1,i)Move the pointer for file f of a distance 1 byte from location i.
b. fread(s,i1,i2,f)Enter i2 dataitems, each of size i1 bytes from file f to string s.
c. fwrite(s,i1,i2,f)send i2 data items,each of size i1 bytes from string s to file f.
d. ftell(f)Return the current pointer position within file f.
e. The data type returned for functions fread,fseek and fwrite is int and ftell is
long int.

34. How is a file opened and file closed?


a. A file is opened using fopen()function. Ex: fp=fopen(filename,mode);
b. A file closed using fclose()function. Ex: fclose(fp);

35. What are the statements used for reading a file? (Nov 2014)
a. FILE*p;Initialize file pointer.
b. fp=fopen(“File_name” ”r”);Open text file for reading.
c. Getc(file_pointer_name);Reads character from file.
d. fgets(str,length,fp); Reads the string from the file.

36. What is the difference between getc() and getchar()? (May 2015)
int getc(FILE * stream) gets the next character on the given input stream „s file
pointer to point to the next character.
int getchar(void) returns the next character on the input stream stdin.
37. Differentiate text file and binary file.
Text file Binary File
a. Data are human readable characters a. Data is in the form of sequence of bytes.
b. Each line ends with a newline character. b. There are no lines or newline character.
c. Ctrl+z or Ctrl+d are end of file character c. An EOF marker is used.
d. Data is read in forward direction only d. Data may be read in any direction.
e. Data is converted into the internal format e. Data stored in file are in same format
before being stored in memory that they are stored in memory

38. What is file pointer?


The pointer to a FILE data type is called as a stream pointer or a file pointer. A file pointer
points to the block of information of the stream that had just been opened

39. State the parameter of fopen function.


The parameter of fopen function are

a. Name of the file to be open


b. Mode of use

40. What is purpose of library function feof()?


The purpose of library function feof() is
a. The C library function int feof(FILE*stream) tests the end-of-
file indicator for the given stream.
b. This function returns a non-zero value when End-of-file indicator
associated with the stream is set, else zero is returned.

41. What is the use of rewind function?


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.
42. List the different modes of opening a file.
The function fopen() has various modes of operation that are listed below

Mode Description
R Opens a text file in reading mode
W Opens or create a text file in writing mode.
A Opens a text file in appended mode.
r+ Opens a text file in both reading and writing mode.
w+ Opens a text file in both reading and writing mode.

43. List the difference between Append and Write.


Write (w) mode and append mode, while opening a file are almost the same. Both are used
towrite in a file. In both the modes, new file is created if it doesn‟t exists already.
The only difference they have is, when you open a file in the write mode, the file
is reset, resulting in deletion of any data already present in the file. While in append
mode this will not happen. Append mode is used to append or add data to the
existing data of file (if any). Hence, when you open a file in append(a) mode, the
cursor is positioned at the end of the present data in the file.

44. Which methods are used to write in to binary files?


The following are the methods are used to write in to binary files
a. fread() function is used to read a binary file.
b. fwrite() functions is used to write a binary file.

45. What is the basic file operation in C?


There are four basic operations that can be performed on any files in C
programming language.
a. Opening / Creating a file.
b. Closing a file
c. Reading a file.
d. Writing in a file.

46. State the fflush() method.


fflush() is typically used for output stream only. Its purpose is to clear (or flush) the
output and move the buffered data to console (in case of stdout) or disk (in case of
file output stream). Syntax. fflush(FILE*ostream);

47. What is the difference between printf() and sprint()?


sprint() writes data to the character array whereas printf(…) writes data to the
standard output device.

48. What is the different file extensions involved when programming in C?


Source codes in C are saved with .C file extensions. Header files or library files
have the .H file extension. Every time a program source code is successfully
compiled, it creates an.OBJ object file, and an executable .EXE file.

49. Is it possible to create your own header files?


Yes, it is possible to create a customized header file. Just include in it the function
prototypes that you want to use in your program, and use the #include directive
followed by the name of your header file.

Part - B

1. Write a C program to perform payroll calculation of


employees using structure.
2. Explain nested structure with an example program.
3. Explain union with an example program.
4. Explain various storage classes in C programming.
5. Explain pre-processor directives in detail with examples.
6. Write a C program to perform file read and write operation.

You might also like