C Unit-3 PPT
C Unit-3 PPT
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;
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
Mode Description
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);