0% found this document useful (0 votes)
43 views11 pages

Chapter 9 Structures and Union 1.define Structure

This document discusses structures and unions in C programming. It defines a structure as a template for grouping variables of different data types under a single name. Structures can contain arrays. Unions are similar to structures but allocate a single shared memory location for all members, equal to the largest member size. Pointers to structures and unions can also be declared. Files in C are collections of bytes stored on disk for program and data storage. Text files contain character streams while binary files do not restrict data types.

Uploaded by

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

Chapter 9 Structures and Union 1.define Structure

This document discusses structures and unions in C programming. It defines a structure as a template for grouping variables of different data types under a single name. Structures can contain arrays. Unions are similar to structures but allocate a single shared memory location for all members, equal to the largest member size. Pointers to structures and unions can also be declared. Files in C are collections of bytes stored on disk for program and data storage. Text files contain character streams while binary files do not restrict data types.

Uploaded by

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

CHAPTER 9 STRUCTURES AND UNION

1.Define structure.
A structure can be considered as a template used for defining a collection of variables
under a single name. Structures help a programmer in grouping elements of different data types
into a single logical unit. This is unlike arrays which permit a programmer to group only
elements of same data type. struct keyword is used to define a structure.

2.Give the syntax for structure.


struct structure_name
{
//Statements
};
or
struct struct_name{ structure_member };
or
struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
-----------
-----------
<data-type> element n;
}struct_var;
Or
struct structure_name
{
data_type member1;
data_type member2;
..
data_type memeber;
};

3.How a Structure is Initialized?


The structure elements are accessed using the dot notation. The individual elements are
initialized as follows :
order_date.day = 9;
order_date.month = 12;
order_date.year = 1995;
One can either initialize a structure by initializing the individual elements as shown
above or by simply listing the element's value inside curly braces, with each value separated by a
comma.
static struct date order_date = {9,12,1995};

4.How a Structure Variables are declared?


It is possible to declare variables of a structure, after the structure is defined. Structure
variable declaration is similar to the declaration of variables of any other data types. Structure
variables can be declared in following two ways.
1) Declaring Structure variables separately
struct Student
{
char[20] name;
int age;
int rollno;
};
struct Student S1 , S2; //declaring variables of Student

2) Declaring Structure Variables with Structure definition


struct Student
{
char[20] name;
int age;
int rollno;
} S1, S2 ;
Here S1 and S2 are variables of structure Student. However this approach is not much
recommended.

5.How structure members are accessed?


Structure members can be accessed and assigned values in number of ways. Structure
member has no meaning independently. In order to assign a value to a structure member, the
member name must be linked with the structure variable using dot . operator also called period or
member access operator. Member operator ‘.’ is used to access the individual structure
members. It is also known as ‘dot operator’ or ‘period operator’.
Syntax:
structure_var.member;
There are two types of operators used for accessing members of a structure.
1. Member operator(.)
2. Structure pointer operator(->)

6.Define an array of structure.


An array of structures is simply an array in which each element is a structure of the same
type. The referencing and subscripting of these arrays (also called structure arrays) follow the
same rules as simple arrays.

7.How an Array of Structure is initialized?


Arrays of structures can be initialized statically or externally from the user.
Static initialization : Case 1
For static initialization, all values are initialized. So, the compile set values for each of the
members. For example,
struct company{
long int employee_id;
char sex;
int age ;
};
company employee[100] = {
1001, 'M', 30;
1002, 'F', 33;
1003, 'M', 35;
};

The compiler will automatically assign the values like the followings:
employee[0].employee_id = 1001;
employee[0].sex = 'M';
employee[0].age = 30;
employee[1].employee_id = 1002;
employee[1].sex = 'F';
employee[i].age = 33;
employee[2].employee_id = 1003;
employee[2].sex = 'M';
employee[2].age = 35;

Static initialization : Case 2


But if any member values are not initialized then the member values are initiated 0 by the
compiler. For example,
struct company{
long int employee_id;
char sex;
int age ;
};
company employee[100] = {
{1001, 'M', 30},
{1002, 'F'},
{1003}
};

employee[0].employee_id = 1001;
employee[0].sex = 'M';
employee[0].age = 30;
employee[1].employee_id = 1002;
employee[1].sex = 'F';
employee[i].age = 0;
employee[2].employee_id = 1003;
employee[2].sex = 0;
employee[2].age = 0;
For the above code, some members are not initialized. So, the compiler will set value
zero to them.

8.Give the format for Structures containing arrays.


Structures can also contain arrays.

struct month {
int number_of_days;
char name[4];
};

static struct month this_month = { 31, "Jan" };

this_month.number_of_days = 31;
strcpy( this_month.name, "Jan" );
printf("The month is %s\n", this_month.name );

Note that the array name has an extra element to hold the end of string null character.

9.Define pointer to structure.


A pointer which is pointing to a structure is known as pointer to structure.

10.Define Nested Structures (Structures within Structures)


Nesting of structures is also permitted in C language. Structures can be used as structures
within structures. It is also called as 'nesting of structures'.
11.Give the syntax for nesting of structures.
struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
-----------
-----------
<data-type> element n;
(or)
struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
-----------
-----------
<data-type> element n;
}inner_struct_var;
}outer_struct_var;

12.Define Structure as function arguments.


In C, structure can be passed to functions by two methods:
1. Passing by value (passing actual value as argument)
2. Passing by reference (passing address of an argument)

13.What is passing structure by value?


A structure variable can be passed to the function as an argument as normal variable. If
structure is passed by value, change made in structure variable in function definition does not
reflect in original structure variable in calling function.

14.What is passing structure by reference?


The address location of structure variable is passed to function while passing it by
reference. If structure is passed by reference, change made in structure variable in function
definition reflects in original structure variable in the calling function.

15.Define Union.
Unions are conceptually similar to structures. A union is a variable which may hold
members of different sizes and types. The syntax of union is also similar to that of structure. The
only differences is in terms of storage. In structure each member has its own storage location,
whereas all members of union uses a single shared memory location which is equal to the size of
its largest data member.
16.Give the syntax for Union.
union union_name
{
<data-type> element 1;
<data-type> element 2;
<data-type> element 3;
}union_variable;
A union is declared using union keyword.

17.Difference between Union and Structure.


 Union allocates one common storage space for all its members
 In union if any of the data element’s value is changed than the other data element value
even changes, i.e. the value of one data element of a union depends on all other data
elements.
 The only major advantage that a union has over structure is to save memory space.
 Union holds value for one data type which requires larger storage among their members.

18.Define Pointer to union.


A pointer which is pointing to a union is known as Pointer to union.

CHAPTER 10 FILE HANDLING


1.Define files.
A file is a collection of bytes stored on a secondary storage device, which is generally a
disk of some kind. A file is simply a machine decipherable storage media where programs and
data are stored for machine usage.

2.Why files are needed?


When the program is terminated, the entire data is lost in C programming. If you want to
keep large volume of data, it is time consuming to enter the entire data. But, if file is created,
these information can be accessed using few commands.
List out the high level I/O functions or What are the two kinds of files?
High level file I/O functions can be categorized as:
1. Text file
2. Binary file

3.List out the Modes of files.


C supports a number of functions that have the ability to perform basic file operations,
which include:
1. Naming a file
2. Opening a file
3. Reading from a file
4. Writing data into a file
5. Closing a file

4.Define text file.


A text file can be a stream of characters that a computer can process sequentially. It is not
only processed sequentially but only in forward direction. For this reason a text file is usually
opened for only one kind of operation (reading, writing, or appending) at any given time.

5.Define binary files.


A binary file is no different to a text file. It is a collection of bytes. In C Programming
Language a byte and a character are equivalent. Hence a binary file is also referred to as a
character stream, but there are two essential differences.
1. No special processing of the data occurs and each byte of data is transferred to or from
the disk unprocessed.
2. C Programming Language places no constructs on the file, and it may be read from, or
written to, in any manner chosen by the programmer.

6.Give the Steps for File operations


1. Create the stream via a pointer variable using the FILE structure:
FILE* spData;
2. Open the file, associating the stream name with the file name.
3. Read or write the data.
4. Close the file.

7.Write down some file functions.


fopen() Creates a new file for read/write operation.
fclose() Closes a file associated with file pointer.
fgetc() Reads the character from current pointer position and advances the pointer to the
next character.
fprintf() Writes all types of data values to the file.
fscanf() Reads all types of data values from a file.

8.Define fopen().
The fopen() function is used to create a new file or to open an existing file. In order to
open a file, use the function fopen(). Use it as:
fp = fopen(filename, mode);
where:
 filename is a string that holds the name of the file on disk (including a path like
/cs/course if necessary).
 mode is a string representing how you want to open the file. Most often you'll open a file
for reading ("r") or writing ("w").

9.Define fclose().
The fclose() function is used for closing opened files. The only argument it accepts is the
file pointer.
General Syntax :
int fclose( FILE *fp );
Here fclose() function closes the file and returns zero on success, or EOF if there is an
error in closing the file. This EOF is a constant defined in the header file stdio.h.

10.Define fscanf() and fprintf()


The functions fprintf() and fscanf() are similar to printf() and scanf() except that these
functions operate on files and require one additional and first argument to be a file pointer.
Give the general format for fprintf and fscanf functions.
The general form of fprintf is
fprintf(fp,”control string”, list);
where fp id a file pointer associated with a file that has been opened for writing.
The general format of fscanf is
fscanf(fp,”controlstring”,list);
This statement would cause the reading of items in the control string.

11.Define fseek function.


The general format of fseek function is a s follows:
fseek(file pointer,offset, position);
This function is used to move the file position to a desired location within the file. Fileptr
is a pointer to the file concerned. Offset is a number or variable of type long, and position in an
integer number. Offset specifies the number of positions (bytes) to be moved from the location
specified bt the position. The position can take the 3 values.
Value Meaning
0 Beginning of the file
1 Current position
2 End of the file.

12.Define getc() and putc().


Function getc() reads a single character from the file which has previously been opened
using a function like fopen(). Function putc() does the opposite, it writes a character to the file
identified by its second argument. The format of both functions is as follows :
getc(in_file);
putc(c, out_file);
Note: The second argument in the putc() function must be a file opened in either write or append
mode.

13.Define ftell().
Function ftell() returns the current position of the file pointer in a stream. The return
value is 0 or a positive integer indicating the byte offset from the beginning of an open file. A
return value of -1 indicates an error. Prototype of this function is as shown below :
long int ftell(FILE *fp);

14.Give the general format for Writing a File.


To write to a file, the file must be opened for writing e.g.
fp = fopen( fname, “w” );

15.Define Sequential files.


Sequential files are generally used in cases where the program processes the data in a
sequential fashion – i.e. counting words in a text file – although in some cases, random access
can be feigned by moving backwards and forwards over a sequential file.

16.Define random access file or Binary files.


True random access file handling, only accesses the file at the point at which the data
should be read or written, rather than having to process it sequentially. A hybrid approach is also
possible whereby a part of the file is used for sequential access to locate something in the
random access portion of the file, in much the same way that a File Allocation Table (FAT)
works.

17.Define rewind() Function.


The rewind() function can be used in sequential or random access C file programming,
and simply tells the file system to position the file pointer at the start of the file. Any error flags
will also be cleared, and no value is returned.

18.List out Formatted Input/Output functions.


fprintf Formatted File Write
fscanf Formatted File Read
printf Formatted Write
scanf Formatted Read
sprintf Formatted String Write
sscanf Formatted String Read
vfprintf Formatted File Write Using Variable Argument List
vprintf Formatted Write Using Variable Argument List
vsprintf Formatted String Write Using Variable Argument List

19.List out File Operation functions.


fclose Close File
fflush Flush File Buffer
fopen Open File
freopen Reopen File
remove Remove File
rename Rename File
setbuf Set Buffer (obsolete)
setvbuf Set Buffer
tmpfile Create Temporary File
Generate Temporary File
tmpnam
Name

20.List out Character Input/Output functions.


Read Character from
fgetc
File
fgets Read String from File
fputc Write Character to File
fputs Write String to File
Read Characters from
getc
File
getchar Read Character
gets Read String
putc Write Character to File
putchar Write Character
puts Write String
ungetc Unread Character

21.List out Block Input/Output functions.


Read Block from
fread
File
fwrite Write Block to File

22.List out File Positioning functions.


fgetpos Get File Position
fseek File Seek
fsetpos Set File Position
Determine File
ftell
Position
rewind Rewind File

23.List out Error Handling functions.


Clear Stream
clearerr
Error
Test for End-of-
feof
File
ferror Test for File Error
Print Error
perror
Message

You might also like