0% found this document useful (0 votes)
2 views

C_unit-V

The document provides an overview of structures, unions, arrays of structures, self-referential structures, type definitions, enumerated types, files, streams, and standard library input/output functions in C programming. It explains how to initialize and access structures and unions, the differences between them, and the various modes of file operations. Additionally, it covers character input/output functions and error handling functions related to file operations.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

C_unit-V

The document provides an overview of structures, unions, arrays of structures, self-referential structures, type definitions, enumerated types, files, streams, and standard library input/output functions in C programming. It explains how to initialize and access structures and unions, the differences between them, and the various modes of file operations. Additionally, it covers character input/output functions and error handling functions related to file operations.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

St.

PAUL’S DEGREE & PG COLLEGE


(Affiliated to Osmania University)
Street No. 8, Himayathnagar, Hyderabad. Ph.No: 27602533

UNIT-V

1) What is Structures? Explain about Initialization of Structures, Accessing


Structuresand Nested Structures?
Structures:
Structure is a collection of elements of different datatypes. The structure is used to create
user defined datatype in C programming language. The structure is also known as “User-
defined” datatype in C.
❖ Creating Structure: To create structure in C we use the keyword called “struct”. We can
create structure variable while defining the structure and we can also create after
terminating structure using struct keyword.
❖ Initialization:
Structure variable can also be initialized at compile time.
Syntax: struct<structure_name>
{
Datatype member1;
Datatype member2;
};
Eg: struct Student
{
char stud_name[30];
int roll_number;
float percentage;
};
struct Student s1={“xyz”,101,9.7};
Or
struct Student s1;
s1.stud_name=”xyz”;
s1.roll_number=101;
s1.percentage=9.7;

➢ Every structure must terminated with semicolon symbol(;).


➢ “struct” is a keyword it must be used in lowercase letter only.
struct student
{
int rollno;
char name[25];
float totalmark;
};
We can now declare structure variables stud1, stud2 as follows struct student stud1,stud2;
❖ Accessing structure Variable:
The different variable types stored in a structure are called its members. The structure
member can be accessed by using a dot (.) operator, so the dot operator is known as
structure member operator.

❖ Memory Allocation of Structures:


When the structures are used in C programming, the memory does not allocate on defining
a structure. The memory is allocated when we create the variable of a particular structure.
Thesize of memory allocated is equal to the sum of memory required by individual members
of that structure.
struct Student{
char stud_name[30]; -------30 bytes
int roll_no; -------02 bytes
float percentage; --------04 bytes
}; ---------------
36 bytes

//Eg:
#include<stdio.h>
#include<conio.h>
void main()
{
struct student
{
char *name;
int rollno;
float totalmark;
};
struct student stud1={"Venkat",1,98};
struct student stud3= {"Shweta",3,97};
struct student stud2={"Arpita",2,99};
clrscr();
printf(“STUDENTS DETAILS:\n”);
printf(“\n\n Roll number:%d\n Name:%s\n Total Marks:%f”, stud1.rollno, stud1.name,
stud1.totalmark);
printf(“\n\n Roll number:%d\n Name:%s\n Total Marks:%f”, stud2.rollno, stud2.name,
stud2.totalmark);
printf(“\n\n Roll number:%d\n Name:%s\n Total Marks:%f”, stud3.rollno, stud3.name,
stud3.totalmark);
getch( );
}
Output :
STUDENTS DETAILS:
Roll number: 1
Name: Venkat
Total Marks:98.000000
Roll number: 2
Name: Arpita
Total Marks:99.000000

Roll number: 3
Name:Shweta
Total Marks:99.000000

Nested Structures: Nesting of structures is also permitted in C language. Nested structures


means that one structure has another structure as member variable.
//Eg:
struct Student
{
char[30] name;
int age;
struct Address
{
char[50] locality;
char[50] city;
int pincode;
} add;
};

2) Discuss about Arrays of Structures and Structures and Functions?


Array of Structure: An array is a collection of data items of the same type. Each element
of the array can be int, char, float, double, or even a structure. structure allows elements of
different data types to be grouped together under a single name. This structure can then be
thought of as a new data type in itself.
An array of structure in C programming is a collection of different datatype variables,
grouped together under a single name.

The structural declaration is as follows −

struct tagname{
datatype member1;
datatype member2;
datatype member n;
};

Structures as function Arguments: We can also pass as structure as function argument or


an array as a function argument.

//Eg:
#include<stdio.h>
Struct Student{
char Name[10];
int roll; };
void show(struct Student st);
void main( ){
struct Student std;
printf(“\n Enter student record:\n”);
printf(:\n Student Name:”);
scanf(:%s”,std.Name);
printf(“\n Enter student roll no:\t”);
scanf(“%d”,&std.roll);
show(std);
}
void show(struct Student st)
{
printf(“\n Student name is %s”,st.Name);
}

3) Explain about self referential structure?


Self Referential structures are those structures that have one or more pointers which point to
the same type of structure, as their member. In other words, structures pointing to the same
type of structures are self-referential in nature.
Syntax: struct structname
{ Datatype member1;
Datatype member2;
...
Datatype member n; };

Types of Self Referential Structures :


➢ Self Referential Structure with Single Link
➢ Self Referential Structure with Multiple Links

⚫ Self Referential Structure with Single Link: These structures can have only one self-
pointer as their member. The following example will show us how to connect the objects
of a self- referential structure with the single link and access the corresponding data
members. The connection formed is shown in the following figure

//Eg:

#include<stdio.h>
struct node{
int data1;
char data2;
struct node*link;
};
int main( ){
struct node ob1;
ob1.link=NULL; //node1

//initialization
ob1.data1=10;
ob1.data2=20;
struct node ob2; //node2

//Initialization
ob2.link=NULL;
ob2.data1=30;
ob2.data2=40;
ob1.link=&ob2;
printf(“%d”,ob1.link->data1);
printf(:\n %d”,ob1.link->data2);
return 0;
}

⚫ Self Referential Structure with Multiple Links: Self referential structures with multiple
links can have more than one self-pointers. Many complicated data structures can be
easily constructed using these structures. Such structures can easily connect to more than
one nodes at a time. The following example shows one such structure with more than one
links.

4) What is Union ?Explain about Initialization of Union,Accessing Union? Difference


between Structure and Union?

The Union is a user-defined data type in C language that can contain elements of the
different data types just like structure. But unlike structures, all the members in the C union
are stored in the same memory location. Due to this, only one member can store data at the
given instance.
Syntax: union union_name {
datatype member1;
datatype member2;
...
};
⚫ Different Ways to Define a Union Variable

We need to define a variable of the union type to start using union members. There are two
methods using which we can define a union variable.
➢ With Union Declaration
➢ After Union Declaration

✓ Defining Union Variable with Declaration


union union_name {
datatype member1;
datatype member2;
...
} var1, var2, ...;

✓ Defining Union Variable after Declaration

union union_name var1, var2, var3...;

⚫ Access Union Members

We can access the members of a union by using the ( . ) dot operator just like structures.
var1.member1;
Initialization of Union in C

The initialization of a union is the initialization of its members by simply assigning the
value to it.
var1.member1 = some_value;

⚫ Initialization of Union in C

The initialization of a union is the initialization of its members by simply assigning the
value to it.
var1.member1 = some_value;

//Eg:
union un {
int member1;
char member2;
float member3;
};

// driver code
int main()
{
// defining a union variable
union un var1;

// initializing the union member


var1.member1 = 15;

printf("The value stored in member1 = %d",


var1.member1);

return 0;
}
Output:
The value stored in member1 = 15

Difference between Structure and Union:

5) Explain about Type Definition(typedef) and Enumerated types?


⚫ Type Defintion(typedef): The typedef is a keyword that is used to provide
existing data types with a new name. The C typedef keyword is used to redefine the
name of already existing data types.
Syntax: typedef existing_name alias_name;

//Eg:
#include <stdio.h>

// defining an alias using typedef


typedef long long ll;
// Driver code
int main()
{
// using typedef name to declare variable
ll var = 20;
printf("%ld", var);

return 0;
}

⚫ Enumerated type: An enum is a special type that represents a group of constants


(unchangeable values).To create an enum, use the enum keyword, followed by the name
of the enum, and separate the enum items with a comma:

//Eg:

#include<stdio.h>

enum week =
{“Sunday”,”Monday”,”Tuesday”,”Wednesday”,”Thursday”,”Friday”,”Saturday”};

int main( ){

enum week today;

today = Wednesday;

printf(“Day %d”,today+1);

return 0;

Output: Day 4

6) What is Files? Explain the Modes of Files?

File is a collection of data that stored on secondary memory like harddisk of a computer.C
langugage supports two types of files.

➢ Text Files (or) ASCII Files

➢ Binary Files

⚫ Text File: The file that contains ASCII codes of data like digits,alphabets and symbols is
called text file (or) ASCII file.
⚫ Binary File: The file that contains data in the form of bytes (o’s and 1’s) is called as
Binary file.

File Operations:

❖ Creating (or) Opening file.

❖ Reading data from a file.

❖ Writing data into a file.

❖ Closing a file.

Modes of Files:
Opening a file:
The fopen() function is used to create a file or open an existing file:

fp = fopen(const char filename,const char mode);

There are many modes for opening a file:

✓ r - open a file in read mode


✓ w - opens or create a text file in write mode
✓ a - opens a file in append mode
✓ r+ - opens a file in both read and write mode
✓ a+ - opens a file in both read and write mode
✓ w+ - opens a file in both read and write mode
✓ Rb- Opens a binary file in reading mode
✓ Wb - Opens or create a binary file in writing mode
✓ Ab - Opens a binary file in append mode
✓ Rb+ - Opens a binary file in both reading and writing mode
✓ Wb+ - Opens a binary file in both reading and writing mode
✓ Ab+ - Opens a binary file in both reading and writing mode

Program to Create a File, Write in it, And Close the File


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

int main()
{

// Declare the file pointer


FILE* filePointer;
// Get the data to be written in file
char dataToBeWritten[50] = "A Computer "
"Science Portal for Geeks";

// Open the existing file GfgTest.c using fopen()


// in write mode using "w" attribute
filePointer = fopen("GfgTest.c", "w");

// Check if this filePointer is null


// which maybe if the file does not exist
if (filePointer == NULL) {
printf("GfgTest.c file failed to open.");
}
else {

printf("The file is now opened.\n");

// Write the dataToBeWritten into the file


if (strlen(dataToBeWritten) > 0) {

// writing in the file using fputs()


fputs(dataToBeWritten, filePointer);
fputs("\n", filePointer);
}

// Closing the file using fclose()


fclose(filePointer);

printf("Data successfully written in file "


"GfgTest.c\n");
printf("The file is now closed.");
}

return 0;
}
7) What is Streams? Explain about Standard Library Input/Output functions and
Character Input/Output functions?
Stream: A stream is a logical entity that represents a file or device that can accept input or
output.All input and output functions in standard C, operate on data streams.
Types of Files:
Stream can be divided into text streams and binary stream.
❖ Text files: Text files are the normal .txt files. To create text files using any simple
texteditors such as Notepad.
❖ Binary files: Binary files are mostly .bin files in computer. Instead of storing data
inplain text, they store it in the binary form(0’s and 1’s).

Standard Library Input/Output functions: Standard library functions are built in


functions in the C compiler that makes things easy for the programmer. The main( )
function is also a standard library function in C.

❖ Formatted Input/Output functions:


fprintf --------- Formatted File Write
fscanf ---------Formatted File Read
printf --------- Formatted Write
scanf ----------Formatted Read
sprintf -------- Formatted String Write
sscanf --------- Formated 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

❖ 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
setvbuf ------ Set Buffer
tmpfile ------ Create Temporary file
tmpname ------ Generate Temporary file name

❖ Character Input/Output functions:


fgetc ---- Read character from file
fgets ---- Read string from file
fputc ---- Write character to file
fputs ----- Write string to file
getc ------ Read characters from file
getchar -- Read character
gets ------ Read string
putc ------ Write character to file
putchar ---- Write character
puts ------- Write string
ungetc ----- Unread character
❖ Block Input/Output functions
Fread ------ Read block from file
Fwrite ----- Write block to file

❖ File positioning functions


fgetpos --------- Get file position
fseek ------------ File seek
fsetpos ------------ Set file posotion
ftell ---------------- Determine file position
rewind -------------Rewind file

❖ Error Handling functions:


clearerr ------- Clear stream error
feof ----------- Test for end of file
ferror -------- Test for file error
perror ----------Print error message

Character Input/Output functions:


C Character functions are used to identify whether the input character is alphabet, digit,
lowercase, uppercase etc.

Character input Functions:


Functions to input a single character are available in 'stdio.h' header file. These functions are:

1. getch( ): 'get' stands for input, 'ch' stands for character. Function getch() is use to input
single character, but it will not display the character entered by the user.
2. getche( ): getche( ) is same as getch() function only the difference is that it will
display the character entered by the user. 'get' stands for input, 'ch' stands for character,
and 'e' stands for echo(display)
3. getchar( ): It will terminate by enter key after inputting a single character.
Syntax: char a = getchar();

Character Output Functions:

1. putch( ): use to print a single character.


Syntax: putch(a);
2. putchar( ): use to print a single character.
Syntax: putchar(a);

You might also like