KEMBAR78
CPL Mod 5 | PDF | Pointer (Computer Programming) | Software Development
0% found this document useful (0 votes)
21 views35 pages

CPL Mod 5

The document explains structures and unions in C programming, detailing their definitions, syntax, and usage. Structures allow for the grouping of heterogeneous data types, while unions share the same memory location for their members, allowing only one member to hold a value at a time. It also covers declaring, accessing, and initializing structures and unions, as well as passing them to functions.

Uploaded by

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

CPL Mod 5

The document explains structures and unions in C programming, detailing their definitions, syntax, and usage. Structures allow for the grouping of heterogeneous data types, while unions share the same memory location for their members, allowing only one member to hold a value at a time. It also covers declaring, accessing, and initializing structures and unions, as well as passing them to functions.

Uploaded by

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

STRUCTURES: “A structure is a collection of heterogeneous data elements referred by

the same name”.

 Drawback of arrays: arrays can be used to represent a collection of elements of the same data
type like int, float etc. They cannot be used to hold a collection of different types of elements.
 Syntax of Structure Definition: structures must be first defined first for their later use. The
syntax for defining a structure is as shown below:

struct structure_name

{
datatype var1;datatype var2;
-------
};
The keyword struct declares a structure. The structure_name represents the name of the
structure. The structure definition is always terminated with a semicolon.

 Example:

struct student
{

int rollno;
char name[26];int marks;
};
In the above example, student is the name of the structure. The members of the student structure
are: name, rollno and marks. A structure itself does not occupy any memory in the RAM. Memory
is allocated only when we create variables using the structure.
a) Declaring Structure Variables: A structure variable declaration is similar to the declaration
of variables of any other data types.
 Syntax for Declaring Structure Variables:
struct structurename var1, var2, …., varN
 Example:

struct student s1, s2, s3;

We can use the keyword typedef to define a structure as follows:typedef


struct

{
int rollno;
char name[26];int marks;
}student;

The name student represents the structure definition associated with it and therefore can be used
to declare structure variables as shown below:
student s1, s2, s3;
b) Accessing Structure Members: We can access and assign values to the members of a
structure in a number of ways. They should be linked to the structure variables in order to
make them meaningful members.
The link between a member and a variable is established using the member operator ‘.’ whichis also
known as dot operator or period operator.
 Syntax for accessing a structure member:
structure-varaible.membername
 Example:
s1.name
s1.rollno

c) Structure Initialization: The values can be initialized in two ways

1) static initialization
2) dynamic initialization

 Example for static initialization:


struct student
{
int rollno;
char name[26];int marks;
};
struct student s1 = {“01”, “nithin”,”96”};struct student s2
= {“02”,”gowda”,”56”};
 Example for dynamic initialization:
scanf(“%d”, &s1.rollno);
scanf(“%s”, s1.name);
scanf(“%d”, s1.marks);
 Program to read and print the student information such as reg.no, name & marks using
structures.

#include<stdio.h>
struct student
{
int roll;
char name[26];
int marks;
};
void main()
{
struct student s1;
printf("Enter the students details\n");
scanf("%d %s %d", &s1.roll, s1.name, &s1.marks);
printf("The details of student:\n");
printf(“Roll no=%d\t Name=%s\t Marks=%d\n”, s1.roll, s1.name, s1.marks);
}

 Program to read and print the employee information such as employee id, name &
salary using structures.

#include<stdio.h>
struct employee
{
int eid;
char name[26];
float salary;
};
void main()
{
struct employee e1;
printf("Enter the employee details\n"); scanf("%d
%s %f", &e1.eid, e1.name, &e1.salary);printf("The
details of employee:\n");
printf(“Emp id=%d\t Name=%s\t Salary=%f\n”, e1.eid, e1.name, e1.salary);
}

ARRAYS OF STRUCTURES: If we want to store details of 100 students it will become


difficult to declare and maintain 100 variables and store the data. Instead, we can declare and array
of structure variables as shown below:

struct student
{
int rollno;
char name[26];int marks[6];
};

struct student s[100];


In the above example, we are declaring an array ‘s’ with 100 elements of the type student which
is a structure.

 C program to enter the information like name, register number, marks in 6 subjects of
N students into an array of structures, find the average & display grade based on average
for each student.

#include<stdio.h>
struct student
{
int roll;
char name[26];int
marks[6];
};
void main()
{
struct student s[10];
int i, n, sum, j;float
avg;
printf("Enter the number of students\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the details of student: \n");
printf("Enter the roll number\n");
scanf("%d",&s[i].roll);
printf("Enter the Name\n");
scanf(“%s”, s[i].name);
printf("Enter the Marks of each subject\n");for
(j=0;j<6;j++)
{
scanf("%d",&s[i].marks[j]);
}
}
for(i=0;i<n;i++)
{
sum=0, avg=0.0;
for(j=0;j<6;j++)
{
sum=sum+s[i].marks[j];
}
avg=(float)sum/6;
printf("Roll Number: %d, Name: %s, Avg Marks: %f \n", s[i].roll, s[i].name, avg);
if(avg>=80 && avg<=100)
{
printf("The grade is DISTINCTION\n");
}
else if(avg>=60 && avg<=79)
{
printf("The grade is FIRST CLASS\n");
}
else if(avg>=40 && avg<=59)
{
printf("The grade is SECOND CLASS\n");
}
else
{
printf("The grade is FAIL\n");
}
}

NESTED STRUCTURES: In C, structures can be nested. A structure can be defined


within in another structure.

 Example of nested structure:

struct student

{
struct name
{

char fname[10];char lname[10];


};

int rollno;int marks;


};
In the above example, student is the outer structure and the inner structure name consists of two
members: fname and lname.

 The members of the inner structure can be accessed as shown below:

outer_structure_variable.inner_structure_variable.member_name;

 Example: s1.n1.fname;

Where s1 is structure variable of student and n1 is a structure variable of name

 Program to read and print the student information such as reg.no, date of birth, name
& total marks using nested structures for date of birth.
#include<stdio.h>
struct dob
{
int day; int
month;int
year;
};
struct student
{
int roll;
char name[26];
struct dob d;
};
void main()
{
struct student s1;
printf("Enter the Student details:\n");
printf("Enter roll no: ");
scanf("%d",&s1.roll);
printf("Enter DOB: ");
scanf("%d %d %d",&s1.d.day,&s1.d.month,&s1.d.year);
printf("Enter name: ");
scanf("%s",s1.name);
printf("Student Details:\n");
printf("Roll:%d\t DOB:%d/%d/%d\t Name:%s" ,s1.roll, s1.d.day, s1.d.month, s1.d.year,
s1.name);
}
PASSING STRUCTURES TO FUNCTIONS: Functions are the basic building blocksof
a C program. So, it is natural for C language to support passing structures as parameters in
functions.

We can pass the C structures to functions in 3 ways:


1) Passing each individual item of the structure as a function argument.
2) Passing the whole structure as a value.
3) Passing the address of the structure (pass by reference).

Syntax for passing the structure variable as a parameter is shown below:


return-type function-name(struct structname var)
{

return expression;
}
1] PASSING EACH INDIVIDUAL ITEM OF THE STRUCTURE AS A FUNCTION
ARGUMENT: the structure data members will be passed to another function by value. It means
the whole structure is not passed, instead of that data members and their values will be passed as
arguemnets. So, this structure can be accessed from called function.

Example for pass individual item as a value:


#include <stdio.h>
struct student
{
int roll;
char name[26];
int marks;
};
struct student s1={01,"Nithin",100};
void display(int,char[],int);
void main()
{
display(s1.roll,s1.name,s1.marks);
}
void display(int roll,char name[],int marks)
{
printf("%d\t",s1.roll);
printf("%s\t",s1.name);
printf("%d\t",s1.marks);
}
2] PASSING ENTIRE STRUCTURE TO FUNCTION AS A VALUE: the whole structure is
passed to another function by value. It means the whole structure is passed to another function
with all members and their values. So, this structure can be accessed from called function.

Example for passing entire structure as a value:


#include <stdio.h>
struct student
{
int roll;
char name[26];
int marks;
};
void display(struct student s1);
void main()
{
struct student s1={01,"Nithin",100};
display(s1);
}
void display(struct student s1)
{
printf("%d\t",s1.roll);
printf("%s\t",s1.name);
printf("%d\t",s1.marks);
}
3] PASSING STRUCTURE TO FUNCTION IN C BY ADDRESS: the whole structure is
passed to another function by address. It means only the address of the structure is passed to
another function. The whole structure is not passed to another function with all members.

Example for passing a structure by Address(reference)::


#include
<stdio.h>struct
student
{
int roll;
char
name[26];int
marks;
};
void display(struct student
*);void main()
{
struct student
s1={01,"Nithin",100};display(&s1);
}
void display(struct student *s1)
{
printf("%d\t",s1->roll);
printf("%s\t",s1->name);
printf("%d\t",s1->marks);
}

Union in C Language
What is Union in C Language?
Union is also a user-defined data type, like structure that contains data members of different
data types.

All the members present in the union share the same location, whereas in the structure each
member got separate memory.
In union, more than one member cannot get memory at the same time, so only one member can
contain a value at a time, whereas in structure all the members can contain different values at
the same time.

Syntax of Declaring Union In C


To create a union in C language, we have to use the union keyword, its basic syntax is -

union union_name
{
//member definitions

Data_Type member1_variable;
Data_Type member2_variable;
Data_Type member3_variable;

};

 union is a keyword with the help of which we create new data type.
 union_name – This is the name of the union data type, you can keep this name as per
your choice like employee, college, item, etc.
 DataType – DataType can contain int, char, float, double anything.
 member1_variable – This is the name of the variable. Every element located inside the
union is called a member.

Example -:

union item
{ int x;
float y;
char z;
};

Note -: The size of the union is equal to the size of the largest data member of the union. For
example – If a union has a union member of 1, 2, 4, 8 bytes, then the size of the union will be 8
bytes.

How to Declare Union Variables In C


The way we declare a structure variable in C language, in the same way, we will declare the union
variable here.
We declare union variables so that union members can easily access and use it anywhere in our
program.

Example -:
union item
{ int x;
float y;
char z;
};

Here union is the keyword and item is a new user-defined data type inside which with the help
of int, float, and char there are three union members declared as x, y, and z. If we want to access
these three members then for this we have to declare a variable of this item data type.

In C language, we can declare a union variable like a structure in two ways -:

1. By using the union keyword inside the main() function.


2. At the end of the union when defining a union.

Method 1 -: Inside the main() function by using the Union keyword


Let’s understand this better through an example

#include<stdio.h>
union item
{ int x;
float y;
char z;
};
void main()
{
union item it1, it2;
}
As I mentioned above, to access the union member, we have to declare the union variable. So
here in this example, we have used union item it1, it2; in the main() function to access union
members. By declaring two union variables named it1, and it2, with the help of which we can
easily access the union member.
Method 2 -: At the end of the union while defining union.
Let’s understand this also through an example -:

Example -:

union item
{ int x;
float y;
char z;
}it1,it2;

 We can also declare the union variable like in the above example.
 The dot (.) operator is used to access the union member and if any union pointer variable
wants to access the union member then -> (structure pointer operator) is used instead of
the dot (.) operator.

Initialization of Union Members In C

We can initialize union members like this –


#include<stdio.h>
union item
{ int x;
float y;
char z;
};
void main()
{
union item it1;

//initialization of each member separately

it1.x = 35;
it1.z = 'a';
it1.y = 15.5;

}
Accessing Members in Union
Like structure, we can also access the union member in these two ways. Let’s learn about these
methods.

 by Dot(.) (member or dot operator)


 by -> (union pointer operator)

Method 1 -: by Dot(.) operator


Through the dot(.) operator, we can access union variables and initialize any value according to
them and print them in the screen.

Examples -:
#include<stdio.h>
union item
{ int x;
float y;

};
void main()
{
union item it1;

//initialization of each member separately

it1.x = 10;

printf( " x = %d \n",it1.x);

it1.y = 15.5;

printf( " y = %f ", it1.y);

Output -:
x = 10
y = 15.5

Example -: if we try to access all union members at the same time


#include<stdio.h>
union item
{ int x;
float y;
char z;
};
void main()
{
union item it1;

//initialization of each member separately

it1.z = 'a';
it1.y = 15.5;

printf( " x = %c y = %f ", it1.z, it1.y);


}

Output -:

x = y = 15. 5

In this example, we wanted to print the stored values in x and y to the screen by accessing x and
y simultaneously. But it did not happen. The compiler was able to print only the value stored in y
because, as I mentioned above, in a union we can access only one union member at a time.

In the earlier example, we had accessed both the members separately and printed their values
in the screen, so the output was absolutely correct.

Note -: If union variable is a pointer then we can access more than one member at a time.

Let’s now learn about the other way to access union member

Method 2: By -> (union pointer operator)


By -> (union pointer operator) we can easily access the union member. Let’s understand this
through an example -:
Example Program:
#include <stdio.h>
union test {
int x;
char y;
};
void main()
{
union test p1;
p1.x = 65;

// p2 is a pointer to union p1
union test* p2 = &p1;

// Accessing union members using pointer


printf("%d %c", p2->x, p2->y);
}

Output -:
65 A
In this example, we created two pointer variables p1, and p2, and used -> to access union
members by pointer variable. Since the ASCII value of 65 is A, the result will print the value of p1
as 65 and the value of p2 as A.

Why We Need Union


A program can have different type of value, if we store these values in different memory space
then memory consumption will be more. But if we use these values by replacing, then we will be
able to store and use different types of values at the same place, this will save a lot of memory.

Union members use the same memory location to store data among themselves. Union is very
useful in embedded programming.

Advantages of Union
It takes very less memory space than the structure
Using union, you can only access the last member directly.
Unions are more useful when you need to store the values of multiple data members at the same
time, sharing the same memory location.
Its size is equal to the size of the largest union member.
Disadvantages of Union
Only one member can be accessed at a time.
More than one union member cannot be used simultaneously.
A memory location is shared between more than one union member.

Different Between Structure and Union In C

Structure Union
The struct keyword is used to The union keyword is used to
define a structure. define union.
Each struct member gets a
All Unio members get only one
different memory location to store
memory location to store data
the data
Changing the value of one data
A change in one data member
member does not affect the other
affects other members.
data member.
You can initialize the value by You can initialize the value by
accessing more than one member accessing only one member at a
at a time. time.
The size of the structure is the The size of the union is equal to
sum of the size of the structure the size of the largest member in
member. the union.
Each struct member gets space in Not every union member gets
memory. space in memory.
It supports flexible array It does not support flexible array
Can access more than one Only one member can be
member at a time. accessed at a time.
Enum or Enumeration

What is Enum or Enumeration?


Enum (Enumeration) is a user-defined data type, used mainly in C language to assign names to
integral constants.
Through enum (Enumeration), we give a meaningful name to integral constants. This makes the
program easy to read and easy to maintain.

The enum keyword is used to define enumeration. Its basic syntax is something like this –
Basic Syntax of enum in C language,
enum enum_name {const1, const2, const3....... };

Here enum is a keyword with the help of which we are defining a new data type.
enum_name is the name of the new data type. You can keep this name as per your wish.
The value of const1 is 0 by default and after that the value of const2, const3 goes on doing 1, 2,
3 like this, you can change these by default values at the time of declaration only if needed.

Example -:
// Changing default values of enum constants
enum month { jan = 1, feb, march ....... };

Declaration of enum variable


In C language, we can declare a variable with enumerated type in two ways -:

 By enum keyword inside the main() function


 At the end of the enumeration itself while defining the enumeration

Method 1 -: By enum keyword inside main() function


Let’s understand this better through an example.
Example -:

#include<stdio.h>
enum month
{ January, February, March, April, May, June, July, August, September, October, November, December
};
void main()
{
enum month m1, m2;
}

Method 2 -: At the end of the enumeration while defining the enumeration.


Let’s understand this also through an example.

enum month
{ January, February, March, April, May, June, July, August, September, October, November, December
}m1, m2;

Note -: In enum variable, we can assign or store only one value at a time.

How to Use Enum


In C language we use Enum in this way

Example -:
#include<stdio.h>
enum month
{ January = 1, February, March, April, May, June, July, August, September, October, November, December
};
void main()
{
enum month m1, m2;
m1 = January;
m2 = February;
printf("Month %d", m1);
printf("\nMonth %d", m2);
}
In this example, we have created a new data type named month which holds the details
of all the months. Since enum variables can store only one value, by assigning January
to m1 and February to m2, the values of m1 and m2 are printed by the printf function.

Its output will be something like this –

Output -: Month 1

Month 2

Why we use enum


When we want our variable to have only a set of values, then we use enum. like
rambow has only 7 colors so here we can use enum to represent these seven colors.

An enum is used to store a value, that can never change, such as month names, seven
days of the week, true, false, etc.

Enum is mostly used with switch-case statements because in switch-case statements


only one statement is executed at a time.

The use of enum increases the readability of the program

Example -:
#include<stdio.h>
enum boolean
{ false , true
}result;

void main()
{
int x;
printf("Enter a number ");
scanf("%d", &x);

if(x%2==0)
result = true;
else
result = false;

if (result)
printf("Even Number");
else
printf("Odd Number");
}
In this example, we created a boolean and created an enum variable named result. In this
program, we took a value from the user and applied an if condition to find out whether this
value is an odd number or an even number, and assigned the result to the result variable.

According to whatever value came in this result variable, we printed that result on the
screen.

Its result was something like this –

Output -:
Enter a number
15
Even number

Important Point About Enum or Enumeration


 If we will not assign any value to the enum name then the compiler by default
assigns 0 to the initial name. and then assigns the value incrementing the name
by 0
 You can change the default value of enum name at the time of declaration as per
your requirement.
 We can declare enum name in any order.
 The enum names created in the same scope should not be same, otherwise
compiler gives error.
File Handling

:Definitions
File: A file is defined as a collection of data stored on the secondary device such as hard
disk. FILE is type defined structure and it is defined in a header file “stdio.h”. FILE is a
derived data type. FILE is not a basic data type in C language.
Input File: An input file contains the same items that might have typed in from
the keyboard.
Output File: An output file contains the same information that might have been
sent to the screen as the output from the program.
Text(data) File:A text file is the one where data is stored as a stream of characters
that can be processed sequentially.

Steps to be perform file manipulations


1. Declare a file pointer variable
2. Open a file and Read the data from the file or write the data into file
3. Close the file

1. Declare a file pointer variable

 Like all the variables are declared before they are used, a file pointer variable
should be declared.

 File pointer is a variable which contains starting address of file.

 It can be declared using following syntax:

FILE *fp;

Example:

#include <stdio.h>
void main()
{
FILE *fp; /* Here, fp is a pointer to a structure FILE */
---------------------------
-------------------------
}

Page 1
2. File open Function

The file should be opened before reading a file or before writing into a file.

Syntax:

FILE *fp; Where,


……..
…….. fp is a file pointer
fp = fopen(filename, mode) fopen() function to open file
mode is “r”,”w”,”a”

 fopen() function will return the starting address of opened file and it is stored in
file pointer.
 If file is not opened then fopen function returns NULL

if (fp == NULL)
{
printf(“Error in opening the file\n”);
exit(0);
}

Modes of File

The various mode in which a file can be opened/created are:

Mode Meaning
“r” opens a text file for reading. The file must exist.
“w” creates an text file for writing.
“a” Append to a text file.

1. Read Mode(“r”)
 This mode is used for opening an existing file to perform read operation.
 The various features of this mode are
 Used only for text file
 If the file does not exist, an error is returned
 The contents of the file are not lost
 The file pointer points to beginning of the file.

Page 2
File position after opening
File contents

EOF(End of File)

2. Write Mode(“w”)
 This mode is used to create a file for writing.
 The various features of this mode are
 If file does not exist, a new file is created.
 If a file already exists with the same name, the contents of the file are erased and
the file is considered as a new empty file.
 The file pointer points to the beginning of the file.

File position after opening


File contents

EOF(End of File)

3. Append Mode(“a”)

 This mode is used to insert the data at the end of the existing file.
 The various features of this mode are
 Used only for text file.
 If the file already exist, the file pointer points to end of the file.

Page 3
 If the file is does not exist. A new file is created.
 Existing data cannot be modified.

File contents

EOF(End of File)

File position after opening

Examples
Read Mode Write Mode
#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
FILE *fp // File Pointer
FILE *fp // File Pointer fp=fopen(“ecb.txt”,”w”); //opening file ecb in writemode
fp=fopen(“civil.txt”,”r”);//opening file civil in readmode
if (fp == NULL) //file does not exist
if (fp == NULL) //file does not exist {
{ printf(“Error in opening the file\n”);//error message
printf(“Error in opening the file\n”);//error message exit(0); //terminate the program
exit(0); //terminate the program }
} fclose(fp); // close the file ecb.txt
fclose(fp); // close the file civil.txt }
}

Page 4
Append Mode
#include<stdio.h>
void main()
{

FILE *fp // File Pointer


fp=fopen(“civil.txt”,”a”); //opening file civil in Append Mode

if (fp == NULL) //file does not exist


{
printf(“Error in opening the file\n”); //error message
exit(0); //terminate the program
}
fclose(fp); // close the file civil.txt

Page 5
3. Closing a file
 When we no longer need a file, that file should be closed.
 This is the last operation to be performed on a file.
 A file can be closed using fclose() function.
 If a file is closed successfully, 0 is returned, otherwise EOF is returned.
Syntax:
fclose(file pointer);

Example:
fclose(fp);

I/O(Input and Output) file functions


The three types of I/O functions to read from or write into the file
I. File I/O functions for fscanf() and fprintf()
II. File I/O functions for strings fgets() and fputs()
III. File I/O functions for characters fgetc() and fputc()

File I/O functions for fscanf() and fprintf()


1.fscanf():
The function fscanf is used to get data from the file and store it in memory.

Syntax:
fscanf(fp, “format string”, address list);
where,
“fp” is a file pointer. It points to a file from where data is read.

“format String”: The data is read from file and is stored in variable s specified in the list ,will
take the values from the specified pointer fp by using the specification provided in format sting.
“address list”: address list of variables.

Note:fsanf() returns number of items successfully read by fscanf function.

Page 6
Example:
FILE *fp FILE *fp
fp=fopen(“name.txt”,”r”); fp=fopen(“marks.txt”,”r”);
fscanf(“fp,”%s”,name); fscanf(“fp,”%d%d%d”,&m1,&m2,&m3);

Note:
1. If the data is read from the keyboard then use stdin in place of fp
2. If the data is read from the file then use fp

2.fprintf():
The function fprintf is used to write data into the file.

Syntax:
fprintf(fp, “format string”, variable list);
where,
“fp” is a file pointer.It points to a file where data to be print.
“format String”: group of format specifiers.
“address list”:list of variables to be written into file

Note:fprinf() returns number of items successfully written by fprintf function.

Example:
FILE *fp FILE *fp
fp=fopen(“name.txt”,”w”); fp=fopen(“marks.txt”,”w”);
fscanf(“fp,”%s”,name); fscanf(“fp,”%d%d%d”,m1,m2,m3);

Note:
1. If the data has to be printer on output screen then use stdout in place of fp
2. If the data has to be written to the file then use fp

Page 7
Example Program
Write a C program to read the contents of two files called as name.txt and usn.text and
merge the contents to another file called as output.txt and display the contents on console
using fscanf() and fprintf().

#include<stdio.h>
#include<stdlib.h>
void main()
{
FILE *fp1,*fp2,*fp3;
char name[20];
int usn;
fp1=fopen("name.txt","r");
fp2=fopen("usn.txt","r");
fp3=fopen("output.txt","w");
for(;;)
{
if(fscanf(fp1,"%s",name)>0)
{
if(fscanf(fp2,"%d",&usn)>0)
{
fprintf(fp3,"%s %d\n",name,usn);
}
else break;
}
else break;
}
fclose(fp1);
fclose(fp2);
fclose(fp3);
fp3=fopen("output.txt","r");
printf("NAME\tUSN\n");
while(fscanf(fp3,"%s %d\n",name, &usn)>0)
{
printf("%s \t%d\n",name,usn);
}
fclose(fp3);
}

Page 8
File I/O functions for fgets() and fputs()
1.fgets()
fgets() is used to read a string from file and store in memory.
Syntax:
ptr=fgets(str,n,fp);
where
fp ->file pointer which points to the file to be read
str ->string variable where read string will be stored
n ->number of characters to be read from file
ptr->If the operation is successful, it returns a pointer to the string read in.
Otherwise it returns NULL.
The returned value is copied into ptr.
Example:
FILE *fp; 1024fp 1024 a.txt 1048
char s[10]; SVITPCD s
SVIT
char *ptr;
fp=fopen(“a.txt”,”r”);
ptr
if(fp==NULL)
1048
{
printf(“file cnnnot be opened);
exit(0);
}
ptr=fgets(s,4,fp);
fclose(fp);

Example Programs:
1.Write a C program to read from file using 1.Write a C program to read string from keyboard
functionfgets. usingfunction fgets.
#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
FILE *fp; char str[15];
char str[15]; char *ptr;
char *ptr; printf(“Enter the string”);
fp=fopen(“name.txt”,”r”): ptr=fgets(str,10,stdin);
if(fp==NULL) if(ptr==NULL)
{ {
printf(“file cannot be opened”); printf(“reading is unsuccessful”);
exit(0); exit(0);

Page 9
} }
ptr=fgets(str,10,fp); printf(“string is”);
if(ptr==NULL) puts(str);
{ fclose(fp);
printf(“reading is unsuccessful”); }
exit(0);
}
printf(“string is”);
puts(str);
fclose(fp);
}

2.fputs()
fputs() is used to write a string into file.
Syntax:
fputs(str,fp);
where
fp ->file pointer which points to the file to be read
str ->string variable where read string will be stored
Example:
FILE *fp,*fp1; 1024 fp 1024 a.txt 1048
char s[10]; SVITPCD s
SVIT
char *ptr;
fp=fopen(“a.txt”,”r”);
fp1=fopen(“b.txt”,”w”); ptr 1048
if(fp==NULL)
{ b.txt
printf(“file cnnnot be opened); SVIT
exit(0);
}
ptr=fgets(s,4,fp);
fputs(s,fp1);
fclose(fp);
fclose(fp1);

Example Program:
1.Write a C program to read from file using function fgets and print into file using fputs
function.
#include<stdio.h>
void main()
{
Page 10
FILE *fp,fp1;
char str[15];
char *ptr;
fp=fopen(“name.txt”,”r”);
fp1=fopen(“output.txt”,”w”);
if(fp==NULL)
{
printf(“file cannot be opened”);
exit(0);
}
ptr=fgets(str,10,fp);
if(ptr==NULL)
{
printf(“reading is unsuccessful”);
exit(0);
}
fputs(str,fp1);
fclose(fp);
fclose(fp1);
}

File I/O functions for fgetc() and fputc()

1.fgetc()
fgetc() function is used to read a character from file and store it in memory.
Syntax:
ch=fgetc(fp);
Example 1:
FILE *fp;
fp=fopen(“sec.txt”,”r”);
ch=fgetc(fp);
Example 2:
FILE *fp; 1024fp 1024 a.txt
char ch; B ch B
fp=fopen(“a.txt”,”r”);
ch=fgets(fp);
fclose(fp);

Page 11
3.fputc()
fgetc() function is used to write a character into a file.
Syntax:
fputc(ch,fp);
Example 1:
FILE *fp;
fp=fopen(“sec.txt”,”w”);
fputc(ch,fp);

Example 2:
FILE *fp,*fp1; 1024 fp 1024 a.txt 1048
char ch; SVITPCD s
SVIT
fp=fopen(“a.txt”,”r”);
fp1=fopen(“b.txt”,”w”); ptr
ch=fges(fp); b.txt
fputc(ch,fp1); SVIT
fclose(fp);
fclose(fp1);

Example Programs
Write a C program to copy one file to another using Write a C program to concatenate two filesusing
fgetc() and fputc() functions. fgetc() and fputc() functions.

#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
FILE *fp1,*fp2; FILE *fp1,*fp2,*fp3;
char ch; char ch;
fp1=fopen(“file1.txt”,”r”); fp1=fopen(“file1.txt”,”r”);
fp2=fopen(“file2.txt”,”w”); fp2=fopen(“file2.txt”,”r”);
while((ch=fegtc(fp1))!=EOF) fp3=fopen(“file3.txt”,”w”);
{
fputc(ch,fp2); while((ch=fegtc(fp1))!=EOF)
} {
fclose(fp1); fputc(ch,fp3);
fclose(fp2); }
}

Page 12
while((ch=fegtc(fp2))!=EOF)
{
fputc(ch,fp3);
}
fclose(fp1);
fclose(fp2);
fclose(fp3);
}

Write a C program for counting the characters, blanks, tabs and lines in file.

#include<stdio.h>
void main()
{
FILE *fp;
char ch;
int cc=0,bc=0,tc=0,lc=0;
fp1=fopen(“file1.txt”,”r”);
while((ch=fegtc(fp1))!=EOF)
{
cc++;
if(ch==’ ’) bc++;
if(ch==’ \n’) lc++;
if(ch==’\t ’) tc++;
}
fclose(fp);
printf(“total number of characters=%d\n”,cc);
printf(“total number of tabs=%d\n”,tc);
printf(“total number of lines=%d\n”,lc);
printf(“total number of blanks=%d\n”,bc);
}

Page 13
Write a program to read data from the keyboard/input stream and write it into a file
called data.txt. Also, read the same data from the file and display it on the screen/output stream.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main()
{
FILE *fp;
char str[200];
fp= fopen("data.txt","w");
if(fp == NULL)
{
printf("error");
exit(1);
}
printf("enter the string");
gets(str);
fprintf(fp, "%s",str);
fscanf(fp, "%s",str);
printf("%s",str);
fclose(fp);
}

Command Line Arguments


 The interface which allows the user to interact with the computer by providing
instructions in the form of typed commands is called command line interface.
 In the command prompt user types the commands.

Example:
In MS_DOS command prompt looks as follows:
C:\>copy T1.c T2.c

Page 14
The above copy command copies contents of T1.c to T2.c. In the above line copy, T1.c and
T2.c are called command line arguments.
Write a C program to accept a file either through command line or as specified by
user during runtime and displays the contents.

#include<stdio.h>
#include<string.h>
void main(int argc,char *argv[])
{
FILE *fp;
char fname[10];
char ch;
if(arg==1)
{
printf(“\n Enter file name\n”);
scanf(“%s”,fname);
}
else
{
strcpy(fname, argv[1]);
}
fp=fopen(fname,”r”);
if(fp==NULL)
{
printf(“cannot open file”);
exit(0);
}
printf(“contents of file are\n”);
while((ch=fgetc(fp))!=EOF)
{
printf(“%c”,ch);
}
}

Page 15

You might also like