35
UNIT-IV http://jayapalmedida.blogspot.in Page 1 The Type Definition(typedef): C supports a feature known as “type definition” that allows users to define an identifier that would represent an existing data type. Its purpose is to redefine the name of an existing variable type. The general syntax of the typedef is as follows, typedef data_type IDENTIFIER; where, typedef is the keyword tells the compiler about the type definition. data_type refers to an existing data type. IDENTIFIER refers the “new” name given to the data type. Usually, uppercase letters are used to make it clear that we are dealing with a renamed data type Note :- using typedef, we are not creating new data types. Instead we are creating only new name for the existing data type. These new data type names are called user-defined data types. Example: Suppose we want to store marks scored in various subjects in variables sub1, sub2 and sub3. These variables can be declared as follows, int sub1, sub2, sub3; Using the user-defined data types, the variables can be declared as shown below, typedef int MARKS; MARKS sub1, sub2, sub3; Advantages :- 1.Provides a meaningful way of declaring the variables. 2.Increase the readability of the program. 3.A complex declaration can be reduced to short and meaningful declaration. 4.typedef is widely used while dealing with structures. Enumerated, Structure ,and Union Types– The Type Definition(typedef), Enumerated types, Structures –Declaration, initialization, accessing structures, operations on structures, Complex structures, structures and functions, Passing structures through pointers, self referential structures, unions, bit fields, C programming examples, command –line arguments, Input and Output – Concept of a file, streams, text files and binary files, Differences between text and binary files, State of a file, Opening and Closing files, file input / output functions (standard library input / output functions for files), file status functions (error handling),Positioning functions, C program examples.

R13Unit4

Embed Size (px)

DESCRIPTION

computer programming

Citation preview

Page 1: R13Unit4

UNIT-IV

h t t p : / / j a y a p a l m e d i d a . b l o g s p o t . i n Page 1

The Type Definition(typedef): C supports a feature known as “type definition” that allows users to define an

identifier that would represent an existing data type. Its purpose is to redefine the name of an existing variable type.

The general syntax of the typedef is as follows,

typedef data_type IDENTIFIER; where,

• � typedef is the keyword tells the compiler about the type definition. • � data_type refers to an existing data type. • � IDENTIFIER refers the “new” name given to the data type. • � Usually, uppercase letters are used to make it clear that we are dealing

with a renamed data type Note :- using typedef, we are not creating new data types. Instead we are creating only new name for

the existing data type. These new data type names are called user-defined data types. Example: Suppose we want to store marks scored in various subjects in variables sub1, sub2 and

sub3. These variables can be declared as follows, int sub1, sub2, sub3;

Using the user-defined data types, the variables can be declared as

shown below, typedef int MARKS; MARKS sub1, sub2, sub3;

Advantages :- � 1.Provides a meaningful way of declaring the variables. � 2.Increase the readability of the program. � 3.A complex declaration can be reduced to short and meaningful declaration. � 4.typedef is widely used while dealing with structures.

Enumerated, Structure ,and Union Types– The Type Definition(typedef), Enumerated types,

Structures –Declaration, initialization, accessing structures, operations on structures, Complex structures,

structures and functions, Passing structures through pointers, self referential structures, unions, bit fields,

C programming examples, command –line arguments, Input and Output – Concept of a file, streams,

text files and binary files, Differences between text and binary files, State of a file, Opening and Closing

files, file input / output functions (standard library input / output functions for files), file status functions

(error handling),Positioning functions, C program examples.

Page 2: R13Unit4

UNIT-IV

h t t p : / / j a y a p a l m e d i d a . b l o g s p o t . i n Page 2

Enumerated types:An enumerated type (also called enumeration or enum) is a data type

consisting of a set of named values called elements, members or enumerators of the type. The enumerator

names are usually identifiers that behave as constants in the language. A variable that has been declared as

having an enumerated type can be assigned any of the enumerators as a value.

Enumerated data type variables can only assume values which have been previously declared.

Declaring an Enumerated Type

To declare an enumerated type, we must declare its identifier with keyword enum and its values. Because

it is derived from integer type, its operations are the same as for integers.

Syntax for defining an enumerated type is as follows,

enum type_Name

{

member1;

member2;

….

….

};

Where,

• enum is the keyword tells the compiler about enumerated type definition.

• enum type_Name together represent the user defined data type.

• member1, member2… are integer constants but represented using descriptive names. These are

called enumerator constants or enumerators.

• The definition terminated with a semicolon.

The syntax for declaring the variables are shown below,

enum type_Name var;

Page 3: R13Unit4

UNIT-IV

h t t p : / / j a y a p a l m e d i d a . b l o g s p o t . i n Page 3

Assigning Values to Enumerated Types :

After an enumerated variable has been declared, we can store values in it. While, the compiler automatically

assigns values to enumerated types starting with 0, the next values are initialized with a value by

adding 1 to previous value.

For example, to set up an enumerated type for the rain status

STRUCTURES Definition:-A structure is a collection of variables of different data types that are logically grouped together

and referenced under same name.

The structure can be declared with the keyword struct following the name and opening

brace with data elements of different type then closing brace with semicolon, as shown below.

Syntax:

struct name

{

type variable1;

type variable2;

.....

.....

type variable n;

};

The variables declared inside the structure are called as members of fields of structure.

Page 4: R13Unit4

UNIT-IV

h t t p : / / j a y a p a l m e d i d a . b l o g s p o t . i n Page 4

Example

struct student

{

int roll_num;

float weight;

int age;

char gender

};

Declaring of structure variables:

Operator used for accessing structure variables: After declaring the structure type, variables and members, the member of the structure

can be accessed by using the structure variable along with the dot (.) operator.

Example:

s1.roll_num=1111;

This stores the value 1111 in roll_num for variable s1

Memory organization of structure variables: struct student s1;

Total space occupied by structure variable s1 is Sizeof(s1)= 2+2+4+1=9 bytes

A structure can be defined using three different ways,

• Tagged Structure

• Structure Variables

• Typedef Structure

syntax:

type <struct name> list of variables separated by comas;

Example: declaring structure variables for above structure;

struct student s1,s2,s3;

Page 5: R13Unit4

UNIT-IV

h t t p : / / j a y a p a l m e d i d a . b l o g s p o t . i n Page 5

Tagged Structure The structure definition associated with the structure name is referred as tagged structure. It does not create

an instance of a structure and Does not allocate any memory.

The general form or syntax of tagged structure definition is as follows,

struct tag_name

{

type1 member1;

type2 member2;

……………

……………

};

Where,

• struct is the keyword which tells the compiler that a structure is being

defined.

• Tag_name is the name of the structure.

• member1, member2 … are called members of the structure.

• The members are declared within curly braces.

• The closing brace must end with the semicolon.

Example: student details using tagged structure

struct student

{

char name [10];

int roll_number;

float avg_marks;

}; // no memory is allocated for the structure

The declaration of the structure variable takes of the form

struct tag_name var1, var2…;

For the above example the variable declaration as follows,

struct student s1; // memory is allocated for the variable

2.Structure Variables :combining both the template declaration and variable declaration in one

statement, is referred as structure variables.

The syntax of tagged structure is as follows,

struct tag_name

{

type1 member1;

type2 member2;

……………

} var1, var2…; Where,

• struct is the keyword which tells the compiler that a structure is being defined.

• tag_name is the name of the structure.

• member1, member2 … are called members of the structure. The members are declared within curly

braces.

Page 6: R13Unit4

UNIT-IV

h t t p : / / j a y a p a l m e d i d a . b l o g s p o t . i n Page 6

• var1, var2… are structure variables .Here each variable occupies memory.

• The closing brace must end with the semicolon.

Example: student details using structure variables

struct student

{

char name [10];

int roll_number;

float avg_marks;

} s1;

We can omit the tag name from the structure definition, the following is valid.

struct

{

char name [10];

int roll_number;

float avg_marks;

} s1, s2;

Declares s1 and s2 as structure variables representing two students. This structure definition and

declaration is normally not used because we can not declare variables in later stage in the program.

3.Typedefined Structure: The structure definition associated with keyword typedef is called type-defined structure. This is the most

powerful way of defining the structure.

The syntax of typedefined structure is

typedef struct

{

type1 member1;

type2 member2;

……

} TYPE_ID;

where,

• typedef is keyword added to the beginning of the definition.

• struct is the keyword which tells the compiler that a structure is being defined.

• member1, member2…are called fields of the structure.

• The closing brace must end with type definition name which in turn ends with semicolon.

Example: Student details

//Structure Definition

typedef struct

{

char name [10];

int roll_number;

float avg_marks;

} STUDENT; //no memory is allocated for structure

/* structure declaration */

STUDENT s1, s2; //memory is allocated for the variables.

Note: Using typedef it is not possible to declare a variable. But, we can have user defined data type.

TYPE_ID can be treated as the new data type.

Page 7: R13Unit4

UNIT-IV

h t t p : / / j a y a p a l m e d i d a . b l o g s p o t . i n Page 7

Initiization of Structure: Like normal variables, the structure variables can also be initialized, but this

initialization can be made at the compile time.

The initialization can be done in two ways for structure variable

struct student s1;

Method1: s1.roll_num=2222;

s1.weight=56.98;

s1.age=18;

s1.gender=’M’

Method 2: struct student s1={2222,56.98,18,’M’};

Write a program to read values into structure student and print the values

#include<stdio.h>

struct student

{

int roll_num;

float weight;

int age;

char gender

};

void main();

{

struct student s1;

s1.roll_num=2222; //initialization

s1.weight=56.98;

s1.age=18;

s1.gender=’M’;

//printing

printf(“Values in structure members for variable s1 are…\n”);

printf(“Roll number:%d\n”,s1.roll_num);

printf(“Weight: %f\n”,s1.weight);

printf(“Height :%d\n”,s1.age);

printf(“Gender:%d”,s1.gender);

}

Array within a structure: an array can be used as a member of a structure

Program to read Student Details and Calculate total and average using structures #include<stdio.h>

int main()

{

struct stud

{

int rno;

char sname[20];

Page 8: R13Unit4

UNIT-IV

h t t p : / / j a y a p a l m e d i d a . b l o g s p o t . i n Page 8

int m1,m2,m3;

};

struct stud s;

int tot;

float avg;

printf("Enter the student roll number: \n");

scanf("%d",&s.rno);

printf("Enter the student name: \n");

scanf("%s",&s.sname);

printf("Enter the three subjects marks: \n");

scanf("%d%d%d",&s.m1,&s.m2,&s.m3);

tot = s.m1 + s.m2 +s.m3;

avg = tot/3.0;

printf("Roll Number : %d\n",s.rno);

printf("Student Name: %s\n",s.sname);

printf("Total Marks : %d\n",tot);

printf("Average : %f\n",avg);

}

Program to read Item Details and Calculate Total Amount of Items #include<stdio.h>

struct item

{

int itemno;

char itemname[20];

float rate;

int qty;

};

int main()

{

struct item i;

float tot_amt;

printf("Enter the Item Number \n");

scanf("%d",&i.itemno);

printf("Enter the Item Name \n");

scanf("%s",&i.itemname);

printf("Enter the Rate of the Item \n");

scanf("%f",&i.rate);

printf("Enter the number of %s purchased ",i.itemname);

scanf("%d",&i.qty);

tot_amt = i.rate * i.qty;

printf("Item Number: %d\n",i.itemno);

printf("Item Name: %s\n",i.itemname);

printf("Rate: %f\n",i.rate);

printf("Number of Items: %d\n",i.qty);

printf("Total Amount: %f",tot_amt);

}

Page 9: R13Unit4

UNIT-IV

h t t p : / / j a y a p a l m e d i d a . b l o g s p o t . i n Page 9

STRUCTURE OPERATIONS Any operation that can be performed on ordinary variables can also be performed on structure members.

But, some operations can not be performed on structure variables. The following sections deals with

operations that carried on structure and structure members.

Copying of structure Variables or members : Copying of two structure variables is achieved using assignment operator. But, one structure variable

can be assigned to another structure variable of the same type.

Example,

struct student

{

char name [10];

float avg;

} ;

struct student a={“rajesh”,66.66};

struct student b;

struct student c={“ravi”,77.77};

a=b; //copies b in to a

b.avg = c.avg; // copies b average in to a.avg

strcpy(b.name, c.name);

Arithmetic Operations on members of Structures :The members of a structure are same to any ordinary

variable and so any operation that can be performed on a variable can also be performed on structure

members.The arithmetic, relational, logical and other various operations can be performed on individual

members of the structures but not on structure variables.

NESTED STRUCTURES A structure which includes another structure is called nested structure i.e a structure can be used as a

member of another structure.

Note: variables of different structures cannot be copied To copy string , use string handling functions

Page 10: R13Unit4

UNIT-IV

h t t p : / / j a y a p a l m e d i d a . b l o g s p o t . i n Page 10

Example:

struct date

{

int day;

int month;

int year;

};

struct student

{

char name [10];

int roll_number;

struct date dob;

int marks [3];

float avg;

} ;

struct student s1;

The syntax for accessing members of a nested structure as follows, outer_structure_variable.innerstructurevariable.membername

The members contained in the inner structure namely day, month and year can be referred to as

s1.dob.day;

s1.dob.month ;

s1.dob.year ;

Page 11: R13Unit4

UNIT-IV

h t t p : / / j a y a p a l m e d i d a . b l o g s p o t . i n Page 11

Structures and functions:

Structure variable as an argument to function The entire Structure can be passed to a function at once as a argumet. Whenever a Structure is passed to a

function the Structure should be declared outside the main(), otherwise it will not be known to all the

functions in the program.

Page 12: R13Unit4

UNIT-IV

h t t p : / / j a y a p a l m e d i d a . b l o g s p o t . i n Page 12

Write a program to pass a structure variable as an argument #include<stdio.h>

#include<conio.h>

#include<string.h>

struct student

{

int rno;

char name[20];

float *avg;

};

int main()

{

struct student s;

float avg=77.7;

clrscr();

strcpy(s.name,"Akhil");

s.roll=111;

s.avg=&avg;

printf("s.Name=%s\n",s.name);

printf("s.roll=%d\n",s.roll);

printf("s.avg=%d\n",*(s.avg));

getch();

return 0;

}

Write a C program that uses functions to perform the following operations:

i) Reading a complex number ii) Writing a complex number

iii) Addition of two complex numbers iv) Multiplication of two complex numbers

#include<stdio.h>

#include<stdlib.h>

#include<conio.h>

struct complex

{

float real,img;

};

/*code for reading complex number*/

struct complex read_complex()

{

struct complex c;

printf("enter real part of complex number");

scanf("%f",&c.real);

printf("enter Imaginary part of complex number");

scanf("%f",&c.img);

return c;

}

/*code for adding complex numbers*/

struct complex add_complex(struct complex c1,struct complex c2)

{

struct complex c3;

Page 13: R13Unit4

UNIT-IV

h t t p : / / j a y a p a l m e d i d a . b l o g s p o t . i n Page 13

c3.real=c1.real+c2.real;

c3.img=c1.img+c2.img;

return c3;

}

/*code for subtraction of complex numbers*/

struct complex sub_complex(struct complex c1,struct complex c2)

{

struct complex c3;

c3.real=c1.real-c2.real;

c3.img=c1.img-c2.img;

return c3;

}

/*code for multiplication of complex numbers*/

struct complex mul_complex(struct complex c1,struct complex c2)

{

struct complex c3;

c3.real=c1.real*c2.real-c1.img*c2.img;

c3.img= c1.img*c2.real+c2.img*c1.real;

return c3;

}

/*code for division of complex numbers*/

struct complex div_complex(struct complex c1,struct complex c2)

{

struct complex c3;

c3.real= (c1.real*c2.real+c1.img*c2.img)/(c2.real*c2.real+c2.img*c2.img);

c3.img= (c1.img*c2.real-c1.real*c2.img)/(c2.real*c2.real+c2.img*c2.img);

return c3;

}

/*code for display of complex number*/

void display_complex(struct complex c)

{

char sign;

printf("The result is:");

if(c.img<0)

{

sign='-';

c.img=-c.img;

}

else

sign='+';

printf("%.2f%ci%.2f",c.real,sign,c.img);

}

int main()

{

int choice;

struct complex a,b,c;

while(1)

{

printf("\n---------------------------------\n");

printf("|Menu for operation on complex numbers|\n ");

printf("----------------------------------\n");

Page 14: R13Unit4

UNIT-IV

h t t p : / / j a y a p a l m e d i d a . b l o g s p o t . i n Page 14

printf("1.Addition \n ");

printf("2.Subtraction \n ");

printf("3.Multiplication \n ");

printf("4.Division \n ");

printf("5.Clear Screen \n ");

printf("6.Exit Menu \n ");

printf("Enter Your Choice: ");

scanf("%d",&choice);

switch(choice)

{

case 1:printf("You Have Selected Addition operation on complex NUmbers\n");

printf("Enter First complex number\n");

a=read_complex();

printf("Enter Second complex Number\n");

b=read_complex();

c=add_complex(a,b);

display_complex(c);

break;

case 2:printf("You Have Selected Subtraction operation on complex NUmbers\n");

printf("Enter First complex number\n");

a=read_complex();

printf("Enter Second complex Number\n");

b=read_complex();

c=sub_complex(a,b);

display_complex(c);

break;

case 3:printf("You Have Selected Multiplication operation on complex Numbers\n");

printf("Enter First complex number\n");

a=read_complex();

printf("Enter Second complex Number\n");

b=read_complex();

c=mul_complex(a,b);

display_complex(c);

break;

case 4:printf("You Have Selected Division operation on complex Numbers\n");

printf("Enter First complex number\n");

a=read_complex();

printf("Enter Second complex Number\n");

b=read_complex();

c=div_complex(a,b);

display_complex(c);

break;

case 5: clrscr();

break;

case 6: exit(0);

default:printf("Invalid choice");

}

}

}

Page 15: R13Unit4

UNIT-IV

h t t p : / / j a y a p a l m e d i d a . b l o g s p o t . i n Page 15

Pointer to a structure:

A Pointer pointing to a structure variable is called Structure Poniter. A Structure Pointer can be used to

store the address of a Structure Variable.

The Members of a structure can be accessed in two ways

1.Using de referencing operator

2.Using selection or arrow operator

An arrow operator (→) is used to refer the Structure members(or elements) when a pointer is used with a

Structure.

EX:

struct emp

{

int empno;

char ename[20];

float sal;

};

struct emp e={123,”ramesh”,50000};

struct emp*eptr;

eptr=&e;

access individual members of a structure using arrow operator

eptr->empno;

eptr->ename;

eptr->sal

Access individual members of a structure using De referencing operator (*eptr).empno;

(*eptr).ename;

(*eptr).sal;

#include<stdio.h>

struct emp

{

int empno;

char ename[20];

float sal;

};

void main()

{

struct emp e={123,"ramesh",50000.00};

struct emp*eptr;

eptr=&e;

printf("\neptr->empno=%d\n",eptr->empno);

printf("eptr->ename=%s\n",eptr->ename);

printf("eptr->sal=%.2f\n",eptr->sal);

printf("\n(*eptr).empno=%d\n",(*eptr).empno);

printf("(*eptr).ename=%s\n",(*eptr).ename);

printf("(*eptr).sal=%.2f\n",(*eptr).sal);

}

Page 16: R13Unit4

UNIT-IV

h t t p : / / j a y a p a l m e d i d a . b l o g s p o t . i n Page 16

SELF REFERENTIAL STRUCTURES:

A Self referential Structure is one that includes with in it’s structure at least one member which is a pointer

to the same structure type. With self referential structures we can create very useful data structures such as

linked lists,trees etc.

Example: struct emp

{

char name[40];

struct emp*next;

};

Applications of Structures :

1. Database Management.(To maintain data about employees in an organisation, book in a library,

items in a Store etc)

2. Changing the size of the Cursor.

3. Clearing the contents of the Screen.

4. Placing the Cursor at appropriate position on Screen.

5. Drawing any graphics Shape on the Screen.

6. Receiving a Key from the Keyboard.

7. Checking the memory size of the Computer.

8. Finding the list of equipment attached to the Computer.

9. Formatting a Floppy.

10. Hiding a file from the Directory.

11. Displaying the Directory of a Disk.

12. Sending the Output to Printer.

13. Interacting with the Mouse.

UNIONS Union is similar to Structure, it is a collection of elements of different data types. the members within a

union will share the same storage area of a member which has highest storage allocation within the

computer’s memory. The union elements are accessed exactly the same way in which the structure elements

are accessed using dot(.) operator

union ex

{

int i;

char ch[2];

}

union ex u;

/* Program to illustrate the use of unions */

#include<stdio.h>

#include<conio.h>

union sample

{

int i;

char ch[2];

};

void main()

{

←--------u.i ---------------→

← u.ch[0]→ ← u.ch[1]→

Page 17: R13Unit4

UNIT-IV

h t t p : / / j a y a p a l m e d i d a . b l o g s p o t . i n Page 17

union sample u;

clrscr();

u.i = 412;

printf("Sizeof(u)=%d\n",sizeof(u));

printf("\n u.i = %d",u.i);

printf("\n u.ch[0] = %d",u.ch[0]);

printf("\n u.ch[1] = %d",u.ch[1]);

u.ch[0] = 'A'; /* Assign a new value */

u.ch[0] = 'B';

printf("\n\n u.i = %d",u.i);

printf("\n u.ch[0] = %c",u.ch[0]);

printf("\n u.ch[1] = %c",u.ch[1]);

getch();

}

Difference between union and structure

SNO STRUCTURE UNION

1 Structure enables us to treat a member of

different variables stored at different places in

memory

union enables us to treat the same space in

memory as a number of different variables

2 As a different variable of a different type on

another occasion.

a union offers a way for a section of memory

to be treated as a variable of one type on one

occasion

3 Use full where all members require d to store

data and can access all variables

simultaneously

Unions are used to conserve memory. Unions

are useful for applications involving multiple

members. here values need not be assigned to

all of the members at any given time.

4 Gives a meaning full result at any point of

time

Attempt to access the wrong type of

information will produce meaningless results.

5 Initialization can be done to any number of

variables at a time

No attempt should be made to initialize more

than one union member

6 All arithmetical or logical operations can be

performed on structure

Performing arithmetical or logical operations

on union variables is not allowed.

7 It is the sum of memory required by all

members of a structure

the amount of memory required is same as that

of the largest member.

8 All members reside in the memory at any

point of time

At any given time, only one member of the

union may actually reside in the storage.

Page 18: R13Unit4

UNIT-IV

h t t p : / / j a y a p a l m e d i d a . b l o g s p o t . i n Page 18

Bitfields: A bitfield allows structures to be subdivided into groups of bits. This process allows multiple variables to be

packed into a single block of memory. Bit fields allows user to access a single bit.

Advantages of bit fields: 1.if storage is limited ,then several Boolean (true/false) variables can be stored in one byte

2.Certain devices transit status information encoded into one or more bits within a byte

3.certain encryption routines need to access the bits within a byte

Example:

Struct employee

{

unsigned gender:1;

unsigned mat_stat:2;

unsigned hobby:3;

unsigned scheme:4;

};

Write a program to illustrate the use of bit fields

#include<stdio.h>

#include<conio.h>

#define MALE 0

#define FEMALE 1

#define SINGLE 0

#define MARRIED 1

#define DIVORCED 2

#define WIDOWED 3

struct employee

{

unsigned gender:1;

unsigned mar_stat:2;

unsigned hobby:3;

unsigned scheme:4;

};

Bit Field Declaration The declaration of a bit-field has the form inside a structure:

struct tag_name

{

type [member_name] : width ;

};

Where

type is the data type of member

member_name is member name

Width is The number of bits in the bit-field.

Page 19: R13Unit4

UNIT-IV

h t t p : / / j a y a p a l m e d i d a . b l o g s p o t . i n Page 19

void main()

{

struct employee e;

clrscr();

e.gender=MALE;

e.mar_stat=DIVORCED;

e.hobby=5;

e.scheme=9;

printf("\nGender=%d",e.gender);

printf("\nMarital status=%d",e.mar_stat);

printf("\nBytes occupied by e=%d", sizeof(e));

getch();

}

command line argument:An executable program that performs a specific task for

operating system is called command. These commands are issued from prompt of operating

system. Some arguments are associated with commands ,hence these arguments are called

command line arguments. These arguments are passed to the program. These arguments are

received by the main() main() can receive two arguments and they are

1.argc 2.argv

1.args:-it counts total number of arguments passed through main().

2.argv:-It is a pointer to an array of character strings which contains all the argument passed

at command prompt

The Skeleton of main along with arguments will look like.

main(int argc, char *argv[])

{

}

Program execution at command prompt: In order to pass one or more arguments to the program when it is executed from the Operating

System, the parameters must follow the program name on the Command line as.

Programme arg1,arg2………. argn

The individual parameters must be separated by a blank space.

The program name will be stored as the first item argv, followed by each of the parameters.

Eg:-

#include<stdio.h>

void main(int argc, char *argv[])

{

int count;

printf(“argc = %d\n”,argc);

for (count =0;count<argc;count++)

printf(“argv[%d] = %s\n”, count, argv[count]);

}

Suppose if the above program is saved as cmdprg.c, then the command line for executing program is like

Page 20: R13Unit4

UNIT-IV

h t t p : / / j a y a p a l m e d i d a . b l o g s p o t . i n Page 20

C:\>cmdprg one two three

Then output will be ------------

argc =4

argv[0] =cmdprg

argv[1] =one

argv[2] =two

argv[3] = three.

/* Demonstrate the use of command-line arguments */

#include<stdio.h>

#include<string.h>

#include<stdlib.h>

int main(int argc,char * argv[])

{

//statements

printf(“the number of arguments: %d\n”,argc);

printf(“the name of the program : %s\n”,argv[0]);

for(int i=1;I<argc; i++)

printf(“user value no. %d: %s\n “, I,argv[i]);

return 0;

}//main

output:

c:>cmdline hello

The number of arguments :2

The name of the program:cmdline

User value number.1:hello

FILES Definition: A file is a collection of bytes stored on a secondary storage device, which is generally a

disk of some kind.

or

A File is a place on disk where a group of related data ( records ) can be stored.

• A file is an external collection of related data treated as a unit.

• The primary purpose of a file is to keep record of data. Record is a group of related

fields. Field is a group of characters they convey meaning.

• Files are stored in auxiliary or secondary storage devices. The two common forms of

secondary storage are disk (hard disk, CD and DVD) and tape.

• Each file ends with an end of file (EOF) at a specified byte number, recorded in file

structure.

• A file must first be opened properly before it can be accessed for reading or writing.

When a file is opened an object (buffer) is created and a stream is associated with the object.

Page 21: R13Unit4

UNIT-IV

h t t p : / / j a y a p a l m e d i d a . b l o g s p o t . i n Page 21

FILE NAME: File name is a string of characters that make up a valid filename. Every operating system

uses a set of rules for naming its files. When we want to read or write files, we must use the

operating system rules when we name a file. The file name may contain two parts, a primary name

and an optional period with extension.

Example: input.txt

program.c

File Operations:- 1. Creating a new file

2. Opening an existing file

3. Reading from a file

4. Writing to a file

5. Moving to a specific location in a file (seek)

6. Closing a file

STREAM Stream is a Sequence of data bytes, which is used to read and write data to a file. The streams that represent

the input data of a program are known as Input Streams, where as the streams that represent the output

data of a program are known as Output Streams.

Input streams gets the data from different input devices such as keyboard and mouse and provide input

data to the program.

Output Streams obtain data from the program and write that on different Output Devices such as Memory

or print them on the Screen.

Standard error: It is connected to the screen & all error messages are output to standard error

Types of Files :

With respect to type of data stored files are categorized into two

Text file : It can be thought of as a stream of characters that can be processed sequentially and in forward

direction only. Formatted Text files contain variable length records must be accessed sequentially,

processing all records from the start of file to access a particular record.

Page 22: R13Unit4

UNIT-IV

h t t p : / / j a y a p a l m e d i d a . b l o g s p o t . i n Page 22

Because of these translations, the number of characters written / read may not be the same as the number

of characters written / read on the external device. Therefore, there may not be a one – to – one

relationship between the characters written / read into the file and those stored on the external

devices.

For example, the data 2345 requires 4 bytes with each character occupying exactly one byte. A text

file cannot contain integers, floating – point numbers etc. converted to their character – equivalent

formats.

2. Binary file: It is collection of bytes like images. Binary files contain fixed length records, They are in

binary format (machine readable) not a human readable format like text files, Binary files can be accessed

directly (i.e. random access). The record structure for a binary file is created using structures, They are

more efficient than text files as conversion from ASCII to binary (reading) and vice versa for writing does

not have to occur , They cannot be read easily by other non-C programs. Binary files are appropriate for

online transaction processing systems.

E.x: Airline reservation, Order processing, Banking systems.

Page 23: R13Unit4

UNIT-IV

h t t p : / / j a y a p a l m e d i d a . b l o g s p o t . i n Page 23

Difference between text file and binary file

Text File Binary File

1. Human readable format. 1. Not in human readable format.

2. Data is stored as lines of characters

with each line terminated by \n which may

be translated into carriage return + line feed.

2. Data is stored on the disk in the same way

as it is represented in the computer memory.

3. Translation of new line character to

carriage return + line feed.

3. No translation of any type.

4. Data can be read using any of the text

editors.

4. Data can be read only by specific

programs written for them.

5. The number of characters written / read

may not be the same as the number of

characters written/read on the external

device such as disk.

5. The number of characters written / read

is same as the number of characters written /

read on the external device such as disk.

6. There may not be a one – to- one

relationship between the characters written

/ read into the file and those stored

on the external devices.

6. There is one – to – one relationship

between the characters written / read into

the file and those stored on the external

devices.

7. The data 2345 requires 4 bytes with

each character requiring one byte. So, it

is stored as 0x 32, 0x 33, and 0 x 34, 0 x 35

(ASCII values) thus requiring 4 bytes.

7. The data 2345 requires 2 bytes and stored

as 0x0929. The data 2345 is requiring 2

bytes.

With respect to type of access files are categorized into two, they are 1.Sequential File: Data stored sequentially, to read the last record of the file, we need to traverse all the

previous records before it. Ex: files on magnetic tapes.

2.Random Access File: Data can be accessed and modified randomly. We can read any record directly.

Ex : files on disks.

STEPS IN WORKING WITH FILES:

1. Establish a Buffer Area

2. Opening a File

3. Reading from a File or Writing to a File

4. Closing a File.

Page 24: R13Unit4

UNIT-IV

h t t p : / / j a y a p a l m e d i d a . b l o g s p o t . i n Page 24

I. Establish a Buffer Area :

The first step is to establish a buffer area, where the information is temporarily stored while being

transferred between the computers memory and the file.

The Buffer Area is established by writing

FILE *ptrvar;

FILE is a Structure which has been defined in the header file “stdio.h” (Standard input/output header

file), which is a link between the Operating System and Program. It is necessary to include the header file

“stdio.h”. The FILE Structure contain information about the file being used, such as its current size, its

location in memory etc. This buffer area allows information to be read from or written to file more fastly.

*prtvar is a pointer variable, which contains address of the Structure FILE.

2. Opening a File :

A File must be opened before it can be created or processed. This association the file name with the

buffer area. It also specifies how the file will be utilized i.e. read-only file, write-only file, or read/write file.

We use the library function fopen() for opening a file.

ptrvar = fopen(filename, mode)

where filename and mode are strings. Filename represent the name of the file, mode represents how

the file opened i.e., read only, write only etc.

The fopen() function returns a pointer to the begins of the buffer area associated with the file. A

NULL value is returned if the file cannot be created or when existing file cannot be found.

The different file opening modes area listed below.

Mode Meaning

“r” Open an existing file for reading only

“w” Open a new file for writing only. If the file exists, its contents are

over written.

“a” Open an existing file for appending (i.e., for adding new information

at the end of the file). A new file will be created if the file does not

exists.

“r+” Open an existing file for both reading and writing.

“w+” Open a new file for both reading and writing. If the file exists, the

contents are over written

“a+” Open an existing file for both reading and appending. A new file

will be created if the file does not exists

To open the file in Binary file mention the mode along with a extra letter ‘b’ as “rb”, “wb”, “rb+”

and so on.

3. Reading /Writing form/to a File :

(i) After opening the file we can read the characters from a file or write the characters into the

file by using the two library functions fgetc() and fputc().

fgetc() ⇒ reach a character from the current position and advances the

pointer position to the next character, and returns the

character that is read.

Eg:- ch = fgetc(ptrvar)

Fputc() ⇒ Writes a character into the file.

Page 25: R13Unit4

UNIT-IV

h t t p : / / j a y a p a l m e d i d a . b l o g s p o t . i n Page 25

Eg:- fputc(ch,ptrvar)

(ii) fscanf() and fprintf() are two functions used for formatted reading and

writing of characters, Strings, integers and floats.

(iii) fread() and fwrite():

These are two functions to read and write structures with file in binary mode.

The Syntax is as follows:

fwrite(&record, sizeof(record),no of records, fileptr);

fread(&record, sizeof(record),no of records, fileptr);

The first argument is the address and the structure.

The second argument is the size of the structure in bytes.

The third argument is the number of structures to read or write.

The last argument is pointer to the file.

4. Closing the File :

Finally, the file must be closed at the end of the program. This can be done by using the function

fclose().

fclose(ptrvar);

It is good programming practice to close a file explicitly, even though C compiler will automatically

close the file.

/* Program to Create a File */ #include<stdio.h>

void main()

{

FILE *fp;

char ch;

fp = fopen(“chars”,’w’);

printf(“Enter the characters(enter * to stop)\n”);

while((ch=getchar())!=’*’)

putc(ch,fp);

printf(“File Created”);

fclose(fp);

}

/* Program to Create a read an Existing File */ #include<stdio.h>

void main()

{

FILE *fp;

char ch;

fp = fopen(“chars”,’r’);

printf(“The contents of the file are:\n”);

while((ch=fgetc(fp))!=EOF)

printf(“%c”,ch);

fclose(fp);

}

Page 26: R13Unit4

UNIT-IV

h t t p : / / j a y a p a l m e d i d a . b l o g s p o t . i n Page 26

TEXT FILES :

Text files are classified in to two types.These are:

1.Formatted Text files

2.Unformatted textfiles

Formatted Text files :

Formatted Text files contain variable length records must be accessed sequentially, processing all records

from the start of file to access a particular record.

For formatted input and output to files we use fprintf and fscanf functions. These functions are the same as

printf and scanf except that the output is directed to the stream accessed by the file pointer, It is a pointer

to Structure FILE

Ex: FILE *fptr

1.fprintf : fprintf is used to write a record to the file.

Syntax : int fprintf (FILE *fptr, const char* fmt,...)

Ex :fprintf (fptr,"%d %s %.2f\n",accNo,name,balance);

Note: fprintf returns the number of characters written or negative if an error occurs.

2.fscanf : Fscanf is used toRead a record from the file.

Syntax : int fscanf (FILE *fptr, const char* fmt, ... )

Ex :fscanf (fptr,"%d %20s %f",&accNo,name, &balance);

Note: fscanf returns the number of input items assigned or EOF if an error or

UNFORMATTED TEXT FILES :

1.fgetc (): This function is used to read the next character from the stream,This is similar to getchar().

Syntax : int fgetc (FILE *stream)

It returns the character (as an integer) or EOF if end of file or an error occurs.

2.fputc() : This function is used to write the character c to the stream.This is similar to putchar(int).

Syntax : int fputc (int c, FILE *stream)

It returns the character or EOF for error.

3.fgets(): This function Reads at most the next n-1 characters from the stream into the array s. Reading stops

after an EOF or a newline. If a newline is read, it is stored into the buffer. A '\0' is stored after the last

character in the buffer. This is similar to gets(char* ).

Syntax : char* fgets (char *s,int n,FILE *stream)

It returns s or NULL if EOF or error occurs

Page 27: R13Unit4

UNIT-IV

h t t p : / / j a y a p a l m e d i d a . b l o g s p o t . i n Page 27

3.fputs() : This is used to write the string s to the stream. This is similar to puts(const char*).

Syntax : int fputs (const char *s, FILE *stream)

It returns EOF for error.

4.feof : The function feof tests for end of file.

Syntax : int feof(FILE *fptr)

feof accepts a pointer to a FILE, It returns non-zero if EOF and zero otherwise.

It is used when reading a file to check whether the EOF has been reached

5.fclose(): used to close an opened file

Syntax: fclose(fp);

Where fp is file pointer

6.fcloseall(): closes all the files that are opened

Syntax:

fcloseall();

7.putw():-writes an integer into a file

Syntax:-

putw(variable,fp);

ex:

int i=5;

putw(i,fp);

8.getw():-Reads an integer from file

Syntax:-

variable=getw(fp);

ex:

int i;

i=getw(fp);

Binary File : Data is in the form of sequence of bytes. There are no lines or newline character.

An EOF marker is used. Data may be read in any direction. Data stored in file are in same format

that they are stored in memory.

1.fwrite():-Writes block of structured data to the file.

The Syntax is as follows:

fwrite(&record, sizeof(record),no of records, fileptr);

The first argument is the address and the structure.

The second argument is the size of the structure in bytes.

The third argument is the number of structures to read or write.

The last argument is pointer to the file.

Page 28: R13Unit4

UNIT-IV

h t t p : / / j a y a p a l m e d i d a . b l o g s p o t . i n Page 28

2.fread():-Reads structured data written by fwrite() function

The Syntax is as follows:

fread(record, sizeof(record),no of records, fileptr);

The first argument is the address and the structure.

The second argument is the size of the structure in bytes.

The third argument is the number of structures to read or write.

The last argument is pointer to the file.

/* Writing records into file in Binary Mode */

#include<stdio.h>

main()

{

FILE *fp;

char choice = ‘y’;

struct emp

{

char name[20];

int age;

float bs;

Page 29: R13Unit4

UNIT-IV

h t t p : / / j a y a p a l m e d i d a . b l o g s p o t . i n Page 29

};

struct emp e;

fp = fopen(“Employee.dat”, “wb”);

if(fp = = NULL)

{

puts(“Cannot open file”);

exit();

}

while (choice = =’y’)

{

printf(“Enter Name, age and Basic Salary”);

scanf(“%s%d%f”, e.name, &e.age, &e.bs);

fwrite(&e,sizeof(e),1,fp);

printf(“Do you want to add one more record (y/n)”);

fflush(stdin);

choice =getch();

}

fclose(fp);

}

/* Read the records from Binary File */

#include<stdio.h>

main()

{

FILE *fp;

struct emp

{

char name[20];

int age;

float bs;

};

struct emp e;

fp = fopen(“Employee.dat”, “rb”);

if(fp = = NULL)

{

puts(“Cannot open file”);

exit();

}

while (fread(&e,sizeof(e),1,fp)

{

printf(“\n Employee Name : %s\n”,e.name);

printf(“\n Employee Age:%d”,e.age);

printf(“\nBasic Salary = %f”,e.bs);

}

fclose(fp);

}

Page 30: R13Unit4

UNIT-IV

h t t p : / / j a y a p a l m e d i d a . b l o g s p o t . i n Page 30

RANDOM ACCESS TO FILES: Sometimes it is required to access only a particular part of the file and not the complete file.This can be

accomplished by using following function.

FILE POSITIONING FUNCTIONS :

File positioning functions have two uses. First, for randomly processing data in disk files, we need to

position the file to read the desired data. Second, we can use the positioning functions to change a file’s

state. Thus, we can change the state of the file pointer using one of the positioning functions.

There three file position functions, � 1. file seek

2.tell location

3. rewind file �

1. fseek(): it is a file function. It positions file pointer on the stream. We can pass three arguments through

this function.

The general format of fseek function is as follows:

fseek( file pointer, offset, position);

This function is used to move the file position to a desired location within the file.

1. Fileptr is a pointer to the file concerned.

2. Offset is a number or variable type long.

3. Position in an integer number.

Offset specifies the number of positions (bytes) to be moved from the location specified at position.

Integer value Constant Location in the file

0 SEEK_SET Beginning of the file

1 SEEK_CUR Current position of file

2 SEEK_END End of file

Ex:

fseek(fp,10,0) or fseek(fp, 10,SEEK_SET)

filepointer is repositioned in forward direction by 10 bytes

Page 31: R13Unit4

UNIT-IV

h t t p : / / j a y a p a l m e d i d a . b l o g s p o t . i n Page 31

2. ftell () :� The ftell function reports the current position of the file marker in the file, relative to the

beginning of the file. ftell () takes a file pointer and returns a number of type long integer, that

corresponds to the current position. Here the return type is long integer because many files have more

than 32,767 bytes. � The syntax of ftell function as follows,

n= ftell(fp);

Page 32: R13Unit4

UNIT-IV

h t t p : / / j a y a p a l m e d i d a . b l o g s p o t . i n Page 32

3.rewind (): � The rewind function simply sets the file position indicator to the beginning of the file as shown in �Figure. This function helps us in reading a file more than once, without having to close and open the file. � Its common use is to change a work from a write state to a read state. However, that to read and write a

file with only one open, we must open it in update mode w+.

Syntax to use rewind function is as follows,

rewind (fp);

Example:

rewind (fp);

n=ftell (fp);

Would assign 0 to n because the file position has been set to the start of the file by rewind.

Write a program to print the location of different characters in a file

#include<stdio.h>

int main()

{

FILE *fp;

char ch;

int pos;

fp=fopen(“sample.txt”,”r”);

if(fp==NULL)

printf(“File opening error”);

else

{

fseek(fp,0,0)

while(!feof(fp)

{

pos=ftell(fp);

ch=getc(fp);

printf(“%d:%c\n”,pos,ch);

Page 33: R13Unit4

UNIT-IV

h t t p : / / j a y a p a l m e d i d a . b l o g s p o t . i n Page 33

}

}

fclose(fp);

return 0;

}

Write a C program to reverse the first n characters in a file. #include <stdio.h>

#include <conio.h>

#include <string.h>

#include <process.h>

void main(int argc, char *argv[])

{

char a[15];

char s[20];

char n;

int k;

int j=0;

int i;

int len;

FILE *fp;

if(argc!=3)

{

puts("Improper number of arguments.");

exit(0);

}

fp = fopen(argv[1],"r");

if(fp == NULL)

{

puts("File cannot be opened.");

exit(0);

}

k=atoi(argv[2]);

n = fread(a,1,k,fp);

a[n]='\0';

len=strlen(a);

for(i=len-1;i>=0;i--)

{

s[j]=a[i];

printf("%c",s[j]);

j=j+1;

}

s[j+1]='\0';

getch();

}

Write a C program to copy the contents of one file to another. #include<stdio.h>

#include<process.h>

Page 34: R13Unit4

UNIT-IV

h t t p : / / j a y a p a l m e d i d a . b l o g s p o t . i n Page 34

#include<conio.h>

void main()

{

FILE *ft,*fs;

int c=0;

clrscr();

fs=fopen("a.txt","r");

ft=fopen("b.txt","w");

if(fs==NULL)

{

printf("Source file opening error\n");

exit(1);

}

else

if(ft==NULL)

{

printf("Target file opening error\n");

exit(1);

}

while(!feof(fs))

{

fputc(fgetc(fs),ft);

c++;

}

printf("%d bytes copied from 'a.txt' to 'b.txt'",c);

c=fcloseall();

printf("%d files closed",c);

}

Write a C program to merge two files into a third file (i.e., the contents of the first file followed by those of the second are put in the third.

#include<stdio.h>

#include<conio.h>

void main()

{FILE *fp1,*fp2,*fp3;

char file1[20],file2[20],file3[20],ch;

puts("Program to merge two files....\n");

puts("Enter first file name:");

gets(file1);

puts("Enter Second file name:");

gets(file2);

puts("Enter Destination file name:");

gets(file3);

fp1=fopen(file1,"r");

fp2=fopen(file2,"r");

fp3=fopen(file3,"w");

if(fp1==NULL&&fp2==NULL)

printf("Error opening file1 and file2.....\n");

else

{

if(fp3==NULL)

Page 35: R13Unit4

UNIT-IV

h t t p : / / j a y a p a l m e d i d a . b l o g s p o t . i n Page 35

printf("Error in creating destination file....\n");

else

{

while((ch=fgetc(fp1))!=EOF)

putc(ch,fp3);

while((ch=fgetc(fp2))!=EOF)

putc(ch,fp3);

}

printf("File Merging Sucessfull....");

fcloseall();

getch();

}

}

Error Handling: While operating on files, there may be a chance of having certain errors which will cause abnormal behavior

in our programs.

1) Opening an file that was not present in the system.

2) Trying to read beyond the end of file mark.

3) Device overflow.

4) Trying to use a file that has not been opened.

5) Trying to perform an operation on a file when the file is opened for another type of operation.

6) Attempting to write to a write-protected file.

1.ferror(fp)� returns non-zero integer value if an error has been detected

otherwise zero 2.perror(string)�prints the string, a colon and an error message specified by the

compiler

/* program on ferror( ) and perror ( ) */

#include<stdio.h>

int main(){

FILE *fp;

char ch;

fp=fopen("str.txt","w");

ch=getc(fp);

if(ferror(fp))

perror(“Error Raised : ");

else

printf("%c",ch);

fclose(fp);

}

You can report Suggestion or errors in this material to

[email protected]