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

C Unit-3 PPT

bj

Uploaded by

24f3000279
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

C Unit-3 PPT

bj

Uploaded by

24f3000279
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Programming Using ‘C’

Language

Unit -3
Structure
• Structure is a user-defined data type that enables us to store the collection
of different data types.
• Each element of a structure is called a member.
• The ,struct keyword is used to declare the structure.
Syntax:
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
struct employee
{ int id;
char name[20];
float salary;
};
Declaring variables of structure:
There are two ways to declare structure variable:
• By struct keyword within main() function
void main()
{
struct employee e1, e2;
}
• By declaring a variable at the time of defining the structure.
struct employee
{ int id;
char name[50];
float salary;
}e1,e2;

Accessing members of the structure:


There are two ways to access structure members:
• By . (member or dot operator)
• By -> (structure pointer operator)
Example:
#include<stdio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
float salary;
}e1,e2;
void main( )
{
e1.id=101;
strcpy(e1.name, "Sonoo Jaiswal");
e1.salary=56000;
e2.id=102;
strcpy(e2.name, "James Bond"); Output:
e2.salary=126000; employee 1 id : 101
printf( "employee 1 id : %d\n", e1.id); employee 1 name : Sonoo Jaiswal
printf( "employee 1 name : %s\n", e1.name); employee 1 salary : 56000.000000
printf( "employee 1 salary : %f\n", e1.salary); employee 2 id : 102
printf( "employee 2 id : %d\n", e2.id); employee 2 name : James Bond
employee 2 salary : 126000.000000
printf( "employee 2 name : %s\n", e2.name);
printf( "employee 2 salary : %f\n", e2.salary); }
Structures as Function Arguments:
Just like other variables, a structure can also be passed to a function.
Example:
#include <stdio.h>
#include <string.h>
struct Books
{
char title[50];
int book_id;
};
void printBook( struct Books book );
void main( )
{
struct Books Book1;
struct Books Book2;
strcpy( Book1.title, "C Programming");
Book1.book_id = 6495407;
strcpy( Book2.title, "Telecom Billing");
Book2.book_id = 6495700;
printBook( Book1 );
printBook( Book2 );
}
void printBook( struct Books book )
{printf( "Book title : %s\n", book.title);
printf( "Book book_id : %d\n", book.book_id);
}
Pointers to Structures:
#include <stdio.h>
#include <string.h>
struct Books
{
char title[50];
int book_id;
};
void printBook( struct Books *book );
void main( )
{
struct Books Book1;
struct Books Book2;
strcpy( Book1.title, "C Programming");
Book1.book_id = 6495407;
strcpy( Book2.title, "Telecom Billing");
Book2.book_id = 6495700;
printBook( &Book1 );
printBook( &Book2 );
}
void printBook( struct Books book )
{printf( "Book title : %s\n", book->title);
printf( "Book book_id : %d\n", book->book_id);
}
Array of Structures:
• The array of structures are used to store information about multiple entities of
different data types.
• The array of structures is also known as the collection of structures.
Example: An array of structures that stores information of 5 students and prints it.
printf("Enter Records of 5 students");
#include<stdio.h> for(i=0;i<5;i++)
#include <string.h> {
printf("\nEnter Rollno:");
struct student scanf("%d",&st[i].rollno);
{ printf("\nEnter Name:");
int rollno; scanf("%s",&st[i].name);
char name[10]; }
}; printf("\nStudent Information List:");
void main() for(i=0;i<5;i++)
{ {
int i; printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
struct student st[5]; }
}
Self-referential structure:
• The self-referential structure is a structure that points to the same type of structure.
• It contains one or more pointers that ultimately point to the same structure.
Example:
#include <stdio.h>
struct node
{
int data1;
char data2;
struct node* link;
};
void main()
{
struct node ob1;
ob1.link = NULL;
ob1.data1 = 10;
ob1.data2 = 20;
struct node ob2;
ob2.link = NULL;
ob2.data1 = 30; Output:
ob2.data2 = 40; 30
ob1.link = &ob2; 40
printf("%d", ob1.link->data1);
printf("\n%d", ob1.link->data2);
}
typedef:
The typedef is a keyword used to provide some meaningful names to the
already existing variable.

Example:
#include <stdio.h>
void main()
{
typedef int unit;
unit i,j;
i=10;
j=20;
printf("Value of i is :%d",i);
printf("\nValue of j is :%d",j);
}
Output:
Value of i is :10
Value of j is :20
Using typedef with structures:

#include <stdio.h>
typedef struct student
{
char name[20];
int age;
}stud;
void main()
{
stud s1;
printf("Enter the details of student s1: ");
printf("\nEnter the name of the student:");
scanf("%s",&s1.name);
printf("\nEnter the age of student:");
scanf("%d",&s1.age);
printf("\n Name of the student is : %s", s1.name);
printf("\n Age of the student is : %d", s1.age);
}
Bit Fields:
• In the bit field, we can explicitly give the width or the range to the data member in
terms of bytes.
• We use the bit fields because-
• Reduces memory consumption.
• To make our program more efficient and flexible.
• Easy to Implement.
Syntax:
dataype data_member : maximum_width_bits
Example:
#include <stdio.h>
struct dob{
int date: 5;
int month: 4;
int year: 12;
};
int main()
{
printf("size of the struct is %ld \n",sizeof(struct dob));
struct dob myDOB={06,11,2001};
printf("my dob is %d-%d-%d",myDOB.date,myDOB.month,myDOB.year);
}
Union
• Union can be defined as a user-defined data type which is a collection of
different variables of different data types in the same memory location.
• Union members share the same memory location.
• The memory occupied by a union will be large enough to hold the largest
member of the union.
• The union keyword is used to declare the structure.

Example:
void main( )
#include <stdio.h> {
#include <string.h> union Data data;
union Data printf( "Memory size occupied by data : %d\n", sizeof(data));
{ }
int i;
float f; Output:
char str[20]; Memory size occupied by data : 20
};
Enumeration
The enum in C is also known as the enumerated type.
It is a user-defined data type that consists of integer values, and it provides
meaningful names to these values.
The use of enum makes the program easy to understand and maintain.
Syntax:
enum enum_name{const1, const2, ....... };
The default value of const1 is 0.
Example 2:
Example 1:
#include <stdio.h> #include<stdio.h>
enum weekdays{Sun=1, Mon, Tue, Wed, Thur enum week{Mon, Tue, Wed, Thur, Fri, Sat,
, Fri, Sat}; Sun};
void main() int main()
{ {
enum weekdays w; enum week day;
w=Mon; day = Wed;
printf("The value of w is %d",w); printf("%d",day);
} return 0;
Output: }
2 Output:
2
File Handling
File handling refers to the method of storing data in the C program in the form of an
output or input that might have been generated while running a C program in a data
file.
Types of Files:
• Text Files
• Binary Files
Text Files:
• The text files are created with the extension .txt by using text editor like notepads.
• These files store info internally in ASCII character format, but when we open these
files, the content/text opens in a human-readable form.
• Text files are very easy to access as well as use.
• The information isn’t very secure in it.
• Text files consume a very large space in storage.
Binary Files:
• The binary files store info and data in the binary format of 0’s and 1’s.
• The binary files are created with the extension .bin in a program.
• It can be accessed very easily as compared to a text file.
• The information becomes much more secure.
• It occupy comparatively lesser space in the storage.
The following operations can be performed on a file.
• Creation of the new file
• Opening an existing file
• Reading from the file
• Writing to the file
• Deleting the file Function Description

fopen() opens new or existing file


Functions for file handling:
fprintf() write data into the file
fscanf() reads data from the file
fputc() writes a character into the file
fgetc() reads a character from file
fclose() closes the file
fseek() sets the file pointer to given position
fputw() writes an integer to file
fgetw() reads an integer from file
ftell() returns current position
rewind() sets the file pointer to the beginning of the file
Opening File: fopen()

Syntax: FILE *fp


file = fopen(“file_name”, “mode”)

Mode Description

r opens a text file in read mode


w opens a text file in write mode
a opens a text file in append mode
r+ opens a text file in read and write mode
w+ opens a text file in read and write mode
a+ opens a text file in read and write mode
rb opens a binary file in read mode
wb opens a binary file in write mode
ab opens a binary file in append mode
rb+ opens a binary file in read and write mode
wb+ opens a binary file in read and write mode
ab+ opens a binary file in read and write mode
Closing File: fclose():
fclose(FILE *fp)

Example:

#include <stdio.h>
void main()
{
FILE * fp;
if (fp = fopen("hello.txt", "r"))
{
printf("File opened successfully in read mode");
}
else
printf("The file is not present! cannot create a new file using r
mode");
fclose(fp);
}
Writing Data to a file:
• We can write data to a file in C using the fprintf(), fputs(), fputc() functions.

fprintf():
• It is used to write a set of characters to the file.
Syntax:
fprintf(FILE *fp, char *string[])

fputs():
• It is used to write a line (character line) to the file.
Syntax:
fputs(FILE *stream , const char *string)
fputc():
• It is used to write a single character to the file.
Syntax:
fputc(char character , FILE *stream)
Example 1:
Example 3:
#include <stdio.h>
#include <stdio.h>
void main()
void main()
{
{
FILE *fp;
FILE *fp;
fp = fopen(“hello.txt", "w");
fp = fopen(“hello.txt", "w");
fprintf(fp, "Hello file by fprintf...\n");
fputc('a',fp);
fclose(fp);
fclose(fp);
}
}
Example 2:
#include <stdio.h>
void main()
{
FILE * fp;
if (fp = fopen("hello.txt", "w"))
{
if(fputs(“Hello file!!!", fp) >= 0)
printf("String written to the file successfully...");
}
fclose(fp);
}
Reading Data for from an existing file:
• We can read content of a file in c using the fscanf() and fgets() and fgetc() functions.
fscanf():
• It is used to read character set i.e strings from the file. It returns the EOF, when all the
content of the file are read by it.
Syntax: fscanf(FILE *stream, const char *charPointer[])
Example 1:
#include <stdio.h>
void main()
{
FILE * file;
char str[500];
if (file = fopen("hello.txt", "r"))
{
while(fscanf(file,"%s", str)!=EOF)
{
printf("%s", str);
}
}
else
printf("Error!”);
fclose(file);
}
fgets():
• It reads a line of characters from file.
Syntax:
char* fgets(char *s, int n, FILE *stream)
fgetc():
• It is used to return a single character from the file. It gets a character from
the file and returns EOF at the end of file.
Syntax:
char* fgetc(FILE *stream)
Example 3:
#include<stdio.h>
Example 2:
void main()
#include<stdio.h>
{
void main()
FILE *fp;
{
char c;
FILE *fp;
fp=fopen(“hello.txt","r");
char text[300];
while((c=fgetc(fp))!=EOF)
fp=fopen(“hello.txt","r");
{
printf("%s",fgets(text,200,fp));
printf("%c",c);
fclose(fp);
}
}
fclose(fp);
}
fseek():
• It is used to set the file pointer to the specified offset.
• It is used to write data into file at desired location.
Syntax:
int fseek(FILE *fp, long int offset, int whence)
offset − This is the number of bytes to offset from whence.
whence − This is the position from where offset is added. It is specified by one
of the following constants −
Constant & Description
Example:
SEEK_SET
#include <stdio.h>
Beginning of file
void main()
{ SEEK_CUR
FILE *fp; Current position of the file pointer
fp = fopen(“hello.txt","w+");
fputs("This is learningpoint", fp); SEEK_END
fseek( fp, 7, SEEK_SET ); End of file
fputs("sonoo jaiswal", fp);
fclose(fp);
}
rewind():
• It sets the file pointer at the beginning of the stream. It is useful if you have to use
stream many times.
Syntax: void rewind(FILE *fp)
Example:
#include<stdio.h>
void main()
{
FILE *fp;
char c;
fp=fopen(“hello.txt","r");
while((c=fgetc(fp))!=EOF)
{
printf("%c",c);
}
rewind(fp);
while((c=fgetc(fp))!=EOF)
{
printf("%c",c);
}
fclose(fp);
}
ftell():
• It returns the current file position of the specified stream.
• We can use ftell() function to get the total size of a file after moving file
pointer at the end of file.
• We can use SEEK_END constant to move the file pointer at the end of file.
Syntax:
long int ftell(FILE *fp)

Example:
#include <stdio.h>
void main ()
{
FILE *fp;
int length;
fp = fopen(“hello.txt", "r");
fseek(fp, 0, SEEK_END);
length = ftell(fp);
fclose(fp);
printf("Size of file: %d bytes", length);
}
putw( ):
• putw( ) function is used for writing a number into file.
Syntax:
putw (int num, FILE *fp);
getw( ):
• getw( ) function is used for reading a number from a file.
Syntax:
int getw (FILE *fp);
Example: Program for storing the numbers from 1 to 10 and to print the same.
#include<stdio.h>
void main( ) fp =fopen ("num.txt", "r");
{ printf ("file content is");
FILE *fp; for (i =1; i<= 10; i++)
int i; {
fp = fopen ("num.txt", "w"); i= getw(fp);
for (i =1; i<= 10; i++) printf ("%d",i);
{ }
putw (i, fp); fclose (fp);
} }
fclose (fp);
File Handling Example: Storing employee information
#include <stdio.h>
void main()
{
FILE *fptr;
int id;
char name[30];
float salary;
fptr = fopen("emp.txt", "w+");
if (fptr == NULL)
{
printf("File does not exists \n");
return;
}
printf("Enter the id\n");
scanf("%d", &id);
fprintf(fptr, "Id= %d\n", id);
printf("Enter the name \n");
scanf("%s", name);
fprintf(fptr, "Name= %s\n", name);
printf("Enter the salary\n");
scanf("%f", &salary);
fprintf(fptr, "Salary= %.2f\n", salary);
fclose(fptr);

You might also like