Sie sind auf Seite 1von 43

Vidya Murugendrappa

Assistant Professor

UNIT 1

ADVANCED C PROGRAMMING CONSTRUCTS

SL.NO TOPICS PAGE NO


A. POINTERS 2
A.1 POINTERS DEFINITION 2
A.2 POINTER VARIABLES 2
A.3 THE POINTER OPERATORS 3
A.4 POINTER EXPRESSIONS 4
A.4.1 POINTER ASSIGNMENTS 4
A.4.2 POINTER CONVERSIONS 5
A.4.3 POINTER ARITHMETIC 6
A.4.4 POINTER COMPARISONS 7
A.5 ARRAYS OF POINTERS 8-10
A.6 FUNCTIONS 10-11
B. STRUCTURES 12-14
B.1 ACCESSING STRUCTURE MEMBERS 14-16
B.2 STRUCTURE ASSIGNMENTS 16
B.3 ARRAYS OF STRUCTURES 16-17
B.4 PASSING ENTIRE STRUCTURES TO FUNCTIONS 18-19
B.5 USING STRUCTURE POINTERS. 20-21
C. UNIONS 21-24
D. FILE HANDLINGS 24-42
E. APPLICATIONS OF DATA STRUCTURES 42
F. SOLVING COMPLEX PROBLEMS 43

Advanced Computer Programming UNIT 1 Page 1


Vidya Murugendrappa
Assistant Professor

A. POINTERS

A.1 POINTERS DEFINITION

a. A pointer is a variable which store the address of another variable in memory.


Example:
If one variable contains the address of another variable, the first variable is said to point to
the second. Figure A illustrates this situation.

Figure A .One variable points to another.

A.2 POINTER VARIABLE


a. A pointer declaration consists of a base type, an *, and the variable name. The general form
for declaring a pointer variable is
type *name;
Where type is the base type of the pointer and may be any valid type. The name of the
pointer variable is specified by name.

Advanced Computer Programming UNIT 1 Page 2


Vidya Murugendrappa
Assistant Professor

Example:

int *a;

Here the declaration of a pointer to be of type int *, the compiler assumes that any address that it
holds points to an integer— whether it actually does or not. (That is, an int * pointer always
''thinks" that it points to an int object, no matter what that piece of memory actually contains.)
Therefore, when the declaration of a pointer should start by its type which is compatible with the
type of object to which that it needs to point.

A.3 POINTER OPERATOR

a. There are two pointer operators: * and &.


b. & operator:
The & is a unary operator that returns the memory address of its
operand. Example:
m = &count;

Here m is placed with the memory address of the variable count . This address is the
computer's internal location of the variable. It has nothing to do with the value of count.
The & is as returning "the address of." Therefore, the preceding assignment statement can
be verbalized as "m receives the address of count.”
c. * operator:
The second pointer operator, *, is the complement of &. It is a unary operator that returns the
value located at the address that follows.
Example:
q = *m;

If m contains the memory address of the variable count. M places the value of count into q.
Here q will have the value 100 because 100 is stored at location 2000, which is the memory
address that was stored in m. You can think of * as "at address." In this case, the preceding
statement can be verbalized as "q receives the value at address m."

Advanced Computer Programming UNIT 1 Page 3


Vidya Murugendrappa
Assistant Professor

A.4 POINTER EXPRESSIONS

a. It involves four special aspects:


i. Pointer Assignments
ii. Pointer Conversions
iii. Pointer Arithmetic
iv. Pointer comparisons

A.4.1 POINTER ASSIGNMENTS

a. Pointer can be used on the right-hand side of an assignment statement to assign its value to
another pointer.
b. When both pointers are the same type, the situation is straightforward.
c. Example:
1. #include <stdio.h>
2. int main(void)
3. {
4. int x = 99;
5. int *p1, *p2;
6. p1 = &x;
7. p2 = p1;
8. /* print the value of x twice */
9. printf(''Values at p1 and p2: %d % d\n", *p1, *p2);
10. /* print the address of x twice */
11. printf("Addresses pointed to by p1 and p2: %p %p", p1, p2);
12. return 0;
13. }

After the assignment sequence


p1 = &x;
p2 = p1;

p1 and p2 both point to x. Thus, both p1 and p2 refer to the same object. Sample
output from the program is as follows.
Values at p1 and p2: 99 99

Advanced Computer Programming UNIT 1 Page 4


Vidya Murugendrappa
Assistant Professor

Addresses pointed to by p1 and p2: 0063FDF0 0063FDF0

A.4.2 POINTER CONVERSIONS

a. Definition: One type of pointer can be converted into another type of pointer.
b. Types of conversions:
i. By explicit casting
ii. By using void * pointer

Explanation:

i. Explicit casting:
Definition:
Conversions are done explicitly by users using the pre-defined functions.
Explicit conversions require a cast operator.
General Form:(type_name) expression
Where:
Type_name indicates to which type of data the expression
is converted.
Example:

#include <stdio.h>

Void main()
{
int sum = 17, count =
5; double mean;

mean = (double) sum / count;


printf("Value of mean : %f\n", mean );

ii. Void * pointer:


A void * pointer is called a generic pointer. The void * pointer is used to
specify a pointer whose base type is unknown.

Advanced Computer Programming UNIT 1 Page 5


Vidya Murugendrappa
Assistant Professor

The void * type allows a function to specify a parameter that is capable of


receiving any type of pointer argument without reporting a type
mismatch. No explicit cast is required to convert to or from a void *
pointer.
General form:- void *pointer_name;
Example:
#include<stdio.h>
int main()
{
int a = 10;
void *ptr ;
ptr=&a;
printf("%d", *(int *)ptr);
return 0;
}

Output:
10

A.4.3 POINTER ARITHMETIC

a. There are only two arithmetic operations that you can use on pointers:
i. Addition
ii. Subtraction
b. Definition of addition:[Increment]
Each time a pointer is incremented, it points to the memory location of the next element
of its base type.
Example:
Let p1 be an integer pointer with a current value of 2000. Also, assume ints are 2 bytes
long. After the expression
p1++;

p1 contains 2002, not 2001. The reason for this is that each time p1 is incremented; it
will point to the next integer.
c. Definition of subtraction:[Decrement]

Advanced Computer Programming UNIT 1 Page 6


Vidya Murugendrappa
Assistant Professor

Each time it is decremented, it points to the location of the previous element.


Example:
Let p1 be an integer pointer with a current value of 2000. Also, assume ints are 2 bytes long.
After the expression
p1--;
causes p1 to have the value 1998.

A.4.4 POINTER COMPARISONS


a. Generally comparison of two pointers can be done by using relational operators:

> Greater Than

< Less Than

>= Greater Than And Equal To

<= Less Than And Equal To

== Equals

!= Not Equal
b. Example:
#include<stdio.h>
int main()
{
int *ptr1,*ptr2;//If ptr1 is of address 1000 and ptr2 is of address
1002 if(ptr2 > ptr1)
printf("Ptr2 is pointing to higher memory location than
ptr1"); return(0);
}

Advanced Computer Programming UNIT 1 Page 7


Vidya Murugendrappa
Assistant Professor

A.5 ARRAYS OF POINTERS

The concept of array is very much bound to that of pointers. An array occupies consecutive
memory location. For example, if we have an array declared as, int arr[] = {1,2,3,4,5}; then in
memory it would be stored as shown below,

1 2 3 4 5
arr[0] arr[1] arr[2] arr[3] arr[4]
1000 1002 1004 1006 1008

Array notation is a form of pointer notation. The name of an array is the starting address of array
in memory. It is also known as base address. In other words, base address is the address of first
element in the array or the address of arr[0].
Now let us use the pointer variable as shown below,
int *ptr;
ptr=&arr[0];
here, ptr is made to point to first element of the array. Consider below example,

#include<stdio.h>
int main()
{
int arr[]={1,2,3,4,5};
printf(―\n address of array = %p %p %p‖, arr, &arr[0], &arr);
}
Output: address of array 1000 1000 1000
Because arr, &arr[0], &arr will give the address of the first element of an array.

Consider below example:


#include<stdio.h>
int main()
{

Advanced Computer Programming UNIT 1 Page 8


Vidya Murugendrappa
Assistant Professor

int arr[]={1,2,3,4,5};
int *ptr;
ptr=arr; /*similar to ptr=&arr[0]*/ printf(―\n starting
address of array = %p‖, ptr);
}
Output: starting address of array 1000
In the above example, you are using pointer ptr, to point to the first element of an array.

Array of pointers
There may be a situation when we want to maintain an array, which can store pointers to an int or char or
any other data type available. Following is the declaration of an array of pointers to an integer:
int *ptr[MAX];
This declares ptr as an array of MAX integer pointers. Thus, each element in ptr, now holds a pointer to
an int value.
Following example makes use of three integers, which will be stored in an array of pointers as follows:

#include <stdio.h>
const int MAX =
3; int main ()
{
int var[] = {10, 100,
200}; int i, *ptr[MAX];
for ( i = 0; i < MAX; i++)
{
ptr[i] = &var[i]; /* assign the address of integer. */
}
for ( i = 0; i < MAX; i++)
{
printf("Value of var[%d] = %d\n", i, *ptr[i] );
}
return 0;
}

Output:
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200

Advanced Computer Programming UNIT 1 Page 9


Vidya Murugendrappa
Assistant Professor

You can also use an array of pointers to character to store a list of strings as follows:
#include <stdio.h>
const int MAX =
4; int main ()
{
char *names[] = {
"Zara Ali",
"Hina Ali",
―Nuha Ali",
"Sara
Ali", };
int i = 0;
for ( i = 0; i < MAX; i++)
{
printf("Value of names[%d] = %s\n", i, names[i] );
}
return 0;
}
Output:
Value of names[0] = Zara Ali
Value of names[1] = Hina Ali
Value of names[2] = Nuha Ali
Value of names[3] = Sara Ali

A.6 Pointers to Functions


Function pointers are pointer variables that point to the address of a function. Function pointers can be
declared, assigned value s and used to access the functions they point to. This is useful technique for
passing a function as an argument to another function. In order to declare a pointer to a function we have
to declare it like a prototype of the function except the name of the function is enclosed between
parentheses () and an asterisk (*) is inserted before the name.

The syntax of declaring a function pointer can be given as,


return_type (*function_pointer_name) (argument_list);

Example: int (*func) (int,int);

Advanced Computer Programming UNIT 1 Page 10


Vidya Murugendrappa
Assistant Professor

NOTE: If you do not put the function within parenthesis, you will end up declaring a function returning a
pointer as shown:
int *func (int,int); /*function returning pointer to int*/

Initializing a function pointer


A function pointer must be initialized before using. If we have declared pointer to a function, then that
pointer can be assigned to the address of the correct function just by using its name like in the case of an
array, a function name is changed into an address when it‘s used in an expression. It is optional to use the
address operator (&) in front of the function name.
For example, if fp is a function pointer and we have a function add() with prototype given
as, int add(int,int);
then writing fp=add; initializes the function pointer fp with the address add().

Calling function using function pointers


1.
#include<stdio.h>
int func(int a, intb)
{
printf(‖\n a= %d‖,
a); printf(‖\n b=
%d‖, b); return 0;
}
int main()
{
int (*fptr) (int,int);
fptr=func;
func(2,3);
fptr(2,3);
return 0;
}
OUTPUT:
a=2
b=3
a=2
b=3

Advanced Computer Programming UNIT 1 Page 11


Vidya Murugendrappa
Assistant Professor

2. #include<stdio.h>

void swap(int *a, int *b)


{
int t=*a;
*a=*b;
*b=t;
}
int main()
{
int a=5, b=3;
printf(―\nbefore swap a=%d, b=%d‖
a,b); swap(&a,&b);
printf(―\nafter swap
a=%d,b=%d\n‖,a,b); return 0;
}
OUTPUT:
Before swap a=5, b=3
After swap a=3, b=5
Explanation: You have passed the address of both variables to the function swap(&a, &b) We have
passed address of two variables from main function to swap function. So we need variable container that
can store the address of integer variables i.e., void swap(int *a, int *b) Thus address of first number will
be collected in ―a‖ pointer variable and second number will be collected in ―b‖ pointer variable.

B. STRUCTURES
A structure is a collection of variables referenced under one name, providing a convenient
means of keeping related information together. A structure declaration forms a template that
can be used to create structure objects (that is, instances of a structure). The variables that make
up the structure are called members. (Structure members are also commonly referred to as
elements or fields.)
The general form of a structure declaration is
struct tag {
type member-name;
type member-name;
type member-name;
.
.
.
} structure-variables;
where either tag or structure-variables may be omitted, but not both.

Usually, the members of a structure are logically related.

Advanced Computer Programming UNIT 1 Page 12


Vidya Murugendrappa
Assistant Professor

For example, the name and address information in a mailing list would normally be represented
in a structure. The following code fragment shows how to declare a structure that defines the
name and address fields.
The keyword struct tells the compiler that a structure is being declared.

The structure declaration is terminated by a semicolon. This is because a structure


declaration is a statement. Also, the structure tag addr identifies this particular data structure and
is its type specifier.

Creating Structure variable:

At this point, no variable has actually been created. Only the form of the data has been
defined. To declare a variable (that is, a physical object) of type addr, write

This declares a variable of type addr called addr_info. Thus, addr describes the form of a
structure (its type), and addr_info is an instance (an object) of the structure.
When a structure variable (addr_info) is declared, the compiler automatically
allocates Sufficient memory to accommodate all of its members.

You can also declare one or more objects when you declare a structure. For example,

Advanced Computer Programming UNIT 1 Page 13


Vidya Murugendrappa
Assistant Professor

#include <stdio.h>
struct addr{
char name[30];
char street[40];
char city[20];
char state[3];
};
main ()
{
struct addr addr_info; // creating the structure variable
struct addr binfo;
struct addr cinfo;
}

OR

B.1 ACCESSING STRUCTURE MEMBERS


Individual members of a structure are accessed through the use of the “.” operator (usually
called the dot operator).
The general form for accessing a member of a structure is,
object_name.member_name

For example, the following statement assigns the ZIP code 12345 to the zip field of the structure
variable addr_info declared earlier.
addr_info.zip = 12345;

Advanced Computer Programming UNIT 1 Page 14


Vidya Murugendrappa
Assistant Professor

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

struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};

int main( )
{
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */

/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming
Tutorial"); Book1.book_id = 6495407;

/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;

/* print Book1 info */


printf( "Book 1 title : %s\n", Book1.title); printf(
"Book 1 author : %s\n", Book1.author); printf(
"Book 1 subject : %s\n", Book1.subject);
printf( "Book 1 book_id : %d\n", Book1.book_id);

/* print Book2 info */


printf( "Book 2 title : %s\n", Book2.title); printf(
"Book 2 author : %s\n", Book2.author); printf(
"Book 2 subject : %s\n", Book2.subject);
printf( "Book 2 book_id : %d\n", Book2.book_id);

return 0;
}

When the above code is compiled and executed, it produces the following result:

Advanced Computer Programming UNIT 1 Page 15


Vidya Murugendrappa
Assistant Professor

Book 1 title : C Programming


Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700

B.2 STRUCTURE ASSIGNMENTS


The information contained in one structure can be assigned to another structure of the same type
using a single assignment statement (=). You do not need to assign the value of each member
separately. The following program illustrates structure assignments:

After the assignment, y.a will contain the value 10.

B.3 ARRAYS OF STRUCTURES


Structures are often arrayed. To declare an array of structures, you must first define a structure
and then declare an array variable of that type. For example, to declare a 100-element array of
structures of type addr defined earlier, write
struct addr addr_list[100];
This creates 100 sets of variables that are organized as defined in the structure addr.

Advanced Computer Programming UNIT 1 Page 16


Vidya Murugendrappa
Assistant Professor

#include<stdio.h>

struct books // structure definition


{
char title[20];
int book_id;
};

main()
{
struct books b[3]; // creating array of structure variable
int i;
for(i=0;i<3;i++)
{
printf(―enter %d book record:‖, i+1);
printf(―enter book name:‖);
scanf(―%s‖,&b[i].title); // accessing structure member using “.” operator
printf(―enter book_id:‖);
scanf(―%d‖,&b[i].book_id); // accessing structure member using “.” operator
}
printf(―displaying book records \n‖);
for(i=0;i<3;i++)
{
printf(―book name is %s‖, b[i].title);
printf(―book_id is %d‖, b[i].book_id);
}
}
Output:
Enter the 1 book record
Enter book name: C programming
Enter book_id:1234

Enter the 2 book record


Enter book name: DBMS
Enter book_id:1673

Enter the 3 book record


Enter book name: ACP
Enter book_id:2765

Displaying the book records:


Book name: C programming
book_id:1234

Book name: DBMS


Book_id:1673

Advanced Computer Programming UNIT 1 Page 17


Vidya Murugendrappa
Assistant Professor

B.4 PASSING ENTIRE STRUCTURES TO FUNCTIONS


There are two ways of passing the entire structure to function:
Passing structure member to function by value
Passing structure member to function by address.
Passing structure member to function by value:
When you are passing a member of a structure to a function, you are passing the value of that
member to the function.
Example: In the below program the whole structure is passed to another function by value.
#include<stdio.h>
#include<string.h>

struct student
{
int id;
char name[20];
float percentage;
};
void func(struct student record);

main()
{
struct student record;
record.id=1;
strcpy(record.name,‖john‖)
; record.percentage=87.5;
func(record);
}
void func(struct student record)
{
printf(―ID is %d \n‖,record.id);
printf(―Name is %s \n‖, record.name);
printf(―percentage is %f \n‖, record.percentage);
}

OUTPUT:
ID is 1
Name is john
Percentage is 87.5

Advanced Computer Programming UNIT 1 Page 18


Vidya Murugendrappa
Assistant Professor

Passing structure member to function by address:


The whole structure is passed to another function by address. It means only the address of
structure is passed to another function. so, structure can be accessed from called function by its
address.

Example:
#include<stdio.h>
#include<string.h>
struct student
{
int id;
char name[20];
float percentage;
};
void func(struct student *record);
main()
{
struct student record;
record.id=1;
strcpy(record.name,‖john‖)
; record.percentage=87.5;
func(&record);
}
void func(struct student *record)
{
printf(―ID is %d \n‖,record->id);
printf(―Name is %s \n‖, record->name);
printf(―percentage is %f \n‖, record->percentage);
}

OUTPUT:
ID is 1
Name is john
Percentage is 87.5

Advanced Computer Programming UNIT 1 Page 19


Vidya Murugendrappa
Assistant Professor

B.5 STRUCTURE POINTERS:


C allows pointers to structures just as it allows pointers to any other type of object.

Declaring a Structure Pointer


Like other pointers, structure pointers are declared by placing * in front of a structure variable's
name.
General Form:
struct <structure_name> *<pointer _name>;

example 1: struct books *book_pointer;


//where, in this declaration books is structure name and book_pointer is the pointer name to the
structure books.
or
example 2: struct student *ptr;
// where, ptr is a pointer to the structure student.

To access the members of a structure using a pointer to that structure, you must use the “–>”
operator.
The –>, usually called the arrow operator, consists of the minus sign followed by a greater than
sign. The arrow is used in place of the dot operator when you are accessing a structure member
through a pointer to the structure
Example:
#include<stdio.h>
#include<string.h>

struct student
{
int id;
char name[30];
};

main()
{

Advanced Computer Programming UNIT 1 Page 20


Vidya Murugendrappa
Assistant Professor

int i;
struct student
record={1,‖Raju‖,90.5}; struct
student *ptr;
ptr=&record;
printf(―record of student1: \n‖);
printf(―ID is : %d\n‖, ptr->id);
printf(―Name is: %s‖, ptr-
>name);
}

OUTPUT:
Record of student1
ID is 1
Name is Raju

C.UNION
A union is a memory location that is shared by two or more different types of variables. A union
provides a way of interpreting the same bit pattern in two or more different ways. Declaring a union
is similar to declaring a structure. A union is declared using union keyword.Its general form is
union tag
{
type member-name;
type member-name;
type member-name;
.
.
.
} union-variables;
For example:
union student
{
int i;
char ch;
};
This declaration does not create any variables.
Declaration of union variable
You can declare a variable either by placing its name at the end of the declaration or by using a separate
declaration statement. To declare a union variable called „s‟ of type student using the definition just

Advanced Computer Programming UNIT 1 Page 21


Vidya Murugendrappa
Assistant Professor

given, write
union student s;

Example:
union student{
int roll;
char name[4];
int marks;
};
Accessing UNION Members
Individual members of a structure are accessed through the use of the “.” operator (usually called the
dot operator).
The general form for accessing a member of a structure is,
object_name.member_name

For example, the following statement above declared ‗s‘ as a variable. So to access the union member
using variable as shown below;
s.roll;
s.name[];
s.marks;
Pointer to union
Pointer which stores address of union is called as pointer to union
Syntax:
Union team t1; // declaring union variable
Union team *ptr; // declaring union pointer variable
Ptr=&t1; // assigning address to union pointer.

The pointer variable can be accessed using “->‟ operator

Example:
#include<stdio.h>

Advanced Computer Programming UNIT 1 Page 22


Vidya Murugendrappa
Assistant Professor

union team
{
char name[10];
int member; char
caption[20];
};
int main()
{
union team t1,*ptr;
ptr=&t1;
t1.name=‖INDIA‖
;
printf(―Team:%s‖,
(*sptr).name);
printf(―Team:%s‖,sptr->name);
return 0;
}

OUTPUT:
Team:INDIA.
Team:INDIA.

All union members occupy ―same memory location‖ i,e; for the union, memory allocated will
be equal to the data memory with maximum size.

In the above example, if roll have size of 2 bytes and name have size of 4 bytes and marks has
2 bytes of size. Then the character array ―name‖ have max size thus ―maximum memory of
the union will be 4bytes‖.
Max memory of union= max memory of union data type
Unions are conceptually similar to structures.
The syntax of union is also similar to that of structure.

The only differences is in terms of storage. In structure each member has its own storage
location, whereas all members of union uses a single shared memory location which is equal to
the size of its largest data member.

Advanced Computer Programming UNIT 1 Page 23


Vidya Murugendrappa
Assistant Professor

This implies that although a union may contain many members of different types, it cannot handle all the members
at same time.
D.FILE HANDLINGS
Console oriented I/O- the term console here refers to the screen-keyboard pair. In console, the program
reads from the keyboard and writes onto the screen.

Major drawback of Console oriented I/O

1. It becomes complicated and time consuming to handle huge amount of data through terminals
2. Data is lost when either the program is terminated or computer is turned off.

Therefore, it is necessary to store data on permanent storage device and read it whenever it is necessary
without losing data which can be done using files.

Files stores information for many purposes and retrieve whenever required by programs. A file
represents a sequence of bytes on a disk where a group of related data is stored.

Streams in C

Advanced Computer Programming UNIT 1 Page 24


Vidya Murugendrappa
Assistant Professor

Standard streams are termed as pre-connected i/p and o/p channels between the terminal and a program.
Therefore, Stream is a logical interface to the device that is connected to the computer.

Keyboar Program Screen

3 standard streams

1. Standard input (stdin) - it is a stream from which the program receives the data.
2. Standard output (stdout) – it is a stream where the program writes its o/p data
3. Standard error (stderr) – iis basically an o/p stream used by the programs to report error
messages.

Types of file

1. Text file stream


2. Binary file stream

Text file stream

It is a stream of sequence (collection) of characters sequentially process by a character. Text file is


opened for only one kind of operation at any given time. Each line in a text file can have maximum up
to 255 characters. When data is written to text file each newline character (is a character used to
represent the end of line of text and beginning of new line) is converted to a carriage return/line feed
character (making the cursor to point to the beginning of the line of text). Similarly when data s read
from a text file, each carriage return/line feed character is converted into newline character.

Binary file stream

It is also a stream o collection of bytes. In binary files, there is no constraint on a file it may be read
from or written to file in any manner (i.e., file is opened for any kind of operation at any given time). It
can be processed sequentially or randomly depending on the need of application.

Advanced Computer Programming UNIT 1 Page 25


Vidya Murugendrappa
Assistant Professor

Advantage


More efficient thantext files because of less memory space and no requirement for conversion from
internal to external.

Disadvantage


Contents of binary file is not human readable.
Processing a file

1. Declare a file pointer.


2. Opening the file.
3. Writing into file.
4. Reading from file.
5. Closing the file.

The File Pointer


The file pointer is the common thread that unites the C I/O system. A file pointer is a pointer to a
Structure of type FILE. It points to information that defines various things about the file, including its
name, status, and the current position of the file. In essence, the file pointer identifies a specific file and
is used by the associated stream to direct the operation of the I/O functions. In order to read or write
files, your program needs to use file pointers. To obtain a file pointer variable, use a statement like this:

Syntax: FILE *<file_pointer_name>;


Example: FILE *fp; //fp is a pointer to the file structure.

Advanced Computer Programming UNIT 1 Page 26


Vidya Murugendrappa
Assistant Professor

Commonly Used C File-System Functions


Name Function
fopen( ) Opens a file

fclose( ) closes a file


putc( ) Writes a character to a file
fputc( ) Same as putc( )
getc( ) Reads a character from a file
fgetc( ) Same as getc( )
fgets( ) Reads a string from a file
fputs( ) Writes a string to a file
fseek( ) Seeks to a specified byte in a file
ftell( ) Returns the current file position
fprintf( ) Is to a file what printf( ) is to the console
fscanf( ) Is to a file what scanf( ) is to the console
feof( ) Returns true if end-of-file is reached
ferror( ) Returns true if an error has occurred
rewind( ) Resets the file position indicator to the beginning of the file
remove( ) Erases a file
fflush( ) Flushes a file

File Handling Functions For Reading And Writing into a File and Strings
1. Opening the File
While opening the file, the following are specified
  Name of the file.
 
Manner in which mode it should be opened (reading, writing, appending, reading/writing).

The function ―fopen‖ is used to open a file. It accepts two arguments. The first is filename and second
is the mode in which it should be opened.
Syntax: FILE *fp=fopen(―filename‖,‖mode‖);
Example: FILE *fp;
fp=fopen(―x.txt‖, ―w‖) //the file x.txt is opened in write mode.

Advanced Computer Programming UNIT 1 Page 27


Vidya Murugendrappa
Assistant Professor

Mode Description
R opens a text file in reading mode
W opens a text file in writing mode
A opens a text file in appending mode
r+ opens a text file in both reading and writing mode
w+ opens a text file in both writing and reading mode
a+ opens a text file in both reading and writing mode
Rb opens a binary file in reading mode
Wb opens or create a binary file in writing mode
Ab opens a binary file in reading mode
rb+ opens a binary file in both reading and writing mode
wb+ opens a binary file in both writing and reading mode
ab+ opens a binary file in both reading and writing mode

2. Closing A File

The fclose()function is used to close an already opened file.

Syntax: int fclose(FILE *fp);


Example: FILE
*fp=open(―w.txt‖,‖w+‖);
fclose(fp);

Here fclose() function closes the file and returns zero on success, or EOF if there is an error in closing t
he file. This EOF is a constant defined in the header file stdio.h.

Example:
Here is an example of opening and closing a file in write mode.
First, a file pointer fp is declared. Then fp is used to open a file named ―test.txt‖ in ‗w‘ mode, which
sta nds for write mode. If fp is null, it means that file could not be opened due to any error.

int main()
{
FILE *fp;
fp = fopen("test.txt","w");
if(fp==NULL)

Advanced Computer Programming UNIT 1 Page 27


Vidya Murugendrappa
Assistant Professor

{
printf("Error in opening file");
}
else
printf("File has been created
successfully"); fclose(fp);
}

3. Functions used for reading and writing a character into the file.
fgetc() and fputc()

fputc() writes a single character to the specified stream (or) outputs the value of character c to the
specified stream.
Syntax: int fputc(int character, FILE stream);
Where,
Character: The character to be writte ;p0gn in the file
stream: pointer to the file in which data will be written.

Return
Type: integer
Value: On success Integer value of the character which is written
On Failure EOF is returned, setting the error indicator.
A character is written in the position specified by the file pointer. After the write
of every character, file pointer increases by one and moves to the next position.
Example:

int main()
{
FILE * fp; //file pointer declaration
int len,i;
char buffer[20] = "Good morning"; //buffer is a string
len = strlen(buffer); //strlen is used to get length of buffer.
fp = fopen ("file.txt","w");

Advanced Computer Programming UNIT 1 Page 29


Vidya Murugendrappa
Assistant Professor

if (fp == NULL) printf ("Error in opening file");


else {
for(i=0; i<len; i++)
//single character is written to file
fputc(buffer[i],fp);
}
fclose (fp); //close of file
}

In this function, a string is defined at the beginning. After opening a file in write mode if successfully
opened, copy the string by one character after another. Here, fputc() is used to write the character in the
file.

fgetc()
It is used to read one by one character from file.
Syntax:
int fgetc ( FILE * stream );

Parameters
stream: Pointer to the file from which data will be read.
Return
type:
It returns the character which is currently pointed by the FILE pointer.
Example:

#include<stdio.h>
int main()
{
FILE * fp;
int count =
0; char ch;
fp = fopen ("file.txt","r");
if (fp == NULL) printf ("Error in opening file");
else {
while((ch = fgetc(fp)) !=
EOF) count++;
}
Advanced Computer Programming UNIT 1 Page 30
Vidya Murugendrappa
Assistant Professor

printf("There are %d words in the


file",count); fclose (fp);
}

Here, a file is opened in read mode. Then until the end of file, characters are read from the file (with
punctuation and space) using fgetc() and count of characters are increased. When it reaches EOF, total
number of character is printed on the screen.

4. Functions used for reading and writing the strings into the file.
fputs() and fgets()

fputs()
It is used to write the string in file.
Prototype:
int fputs(const char* str, FILE* stream );

Parameters
str:- constant character pointer or string that is to be written in the file. stream:- pointer to the file in
which the data is to be written.

Return
Type: integer
Value: On success Non negative value and
On failure: End of file(EOF), setting the error indicator

fgets()
fgets is used to read data from
file. Prototype:
char* fgets(char* str,int count,FILE* stream);

Parameters

Advanced Computer Programming UNIT 1 Page 31


Vidya Murugendrappa
Assistant Professor

str: character pointer that will point to the returned data from file.
count: integer that is the maximum count of character to return from the file. If the number is n, then (n-
1) character is returned from the file. If the number of characters is less than n-1, then full data from the
file will be returned.
stream: pointer to the file from which the data will be fetch

Return:
Type: character pointer(char*)
Value: On success String which is read
On failure Null pointer, setting the error indicator

Example fputs and fgets

int main()
{
FILE* fp;
char ch[20];

fp = fopen("testFile.txt","w");
if(fp == NULL)
printf("Error in creating
file"); else
fputs("This is a test
file",fp); fclose(fp);

fp = fopen("testFile.txt","r");

if(fp == NULL)
{
printf("Error in opening file");
}
else
{
fgets(ch,20,fp);
printf("\n%s",ch);
}

Advanced Computer Programming UNIT 1 Page 32


Vidya Murugendrappa
Assistant Professor

getch();
return 0;
}

In this example, a file is opened in write mode. After successful opening, a string is put in the file using
fputs() function. The file is then closed and again opened in read mode. Next using fgets() function,
twenty characters are read from starting position of the file and printed it on the console.

5. fprintf() and fscanf()


fprintf(): It works like printf(), with some differences. While printf() works for standard ouput, fprintf()
is for file writing. The protype is:

int fprintf(FILE * stream, const char* str);

Parameters
stream: pointer to the file in which the data is to be written.
str: character pointer to the data to be written, which can include the format of the data.

Return
Type: integer
Value: On success number of characters which is written
On Failure Negative number.

fscanf(): It works like scanf() function, with some differences. While scanf() works for standard input,
fscanf() is for file reading.

The prototype is:


int fscanf(FILE * stream, const char* str);

Parameters
stream: pointer to the file from which the data is to be read.
str: character pointer to the data to be read. It is mainly the format of the data.
Advanced Computer Programming UNIT 1 Page 33
Vidya Murugendrappa
Assistant Professor

Return
Type: integer
Value: On success number of arguments which is filled
On failure error indicator is set and EOF is returned.

Example:
#include<stdio.h>
Struct emp
{
char name[10];
int age;
}
void main()
{
struct emp e;
FILE *p,*q;
p=fopen(―one.txt‖,‖a‖);
q=fopen(―one.txt‖,‖r‖);
printf(―enter name and age: ―);
scanf(―%s %d‖,
e.name,&e.age); fprintf(p,‖%s
%d‖, e.name,e.age); fclose(p);
do
{
fscanf(q, ―%s %d‖, e.name,
&e.age); printf(―%s %d‖, e.name,
e.age);
}
while(!feof(q));
Advanced Computer Programming UNIT 1 Page 34
Vidya Murugendrappa
Assistant Professor

fclose(q);
return 0;
}

In the above program, we have declared emp structure with members name and age. We have declared
two file pointers p to open file in append mode and q in read mode and structure variable ―e‖ of
employee (emp) structure. Using fprintf and fscanf we write the data into file and read the data from
file.

6. fseek()
It is used to set file pointer to any position.

Advanced Computer Programming UNIT 1 Page 35


Vidya Murugendrappa
Assistant Professor

Prototype is:
int fseek ( FILE * stream, long int offset, int origin );

Parameters
Stream: pointer to a file.
Offset: Number of bytes or characters from the origin.
Origin: The original position is set here. From this position, using the offset, the file pointer is set to a
new position. Generally, three positions are used as origin:

SEEK_SET - Beginning of file


SEEK_CUR - Current position of the file pointer
SEEK_END - End of file

Return
Type: Integer
Value: On success Zero (0)
On failure Non-Zero

Advanced Computer Programming UNIT 1 Page 36


Vidya Murugendrappa
Assistant Professor

Example:
#include<stdio.h>
int main()
{
FILE *fp;
fp=fopen(―file.txt‖,‖w‖
); if(fp==NULL)

printf(―error in opening
file‖); else
{

fputs(―I am supporter of france‖,


fp); fseek(fp,18,SEEK_SET);
fputs(fp,0,SEEK_CUR);
fputs(― and
Portugal‖,fp); fclose(fp);
}
return 0;
}

Using SEEK_SET and offset, the word France is replaced by Brazil. Then by using SEEK_CUR, and
position is appended with the string(and Portugal).

7. fwrite() and fread()


fwrite(): It is used for file writing. Prototype is:

size_t fread(const void* ptr,size_t size,size_t count,FILE* stream)

Parameters:
ptr: pointer to the data which will be stored.
size: the size of data elements (in byte) to be written.

Advanced Computer Programming UNIT 1 Page 37


Vidya Murugendrappa
Assistant Professor

count: number of data elements to be written.


stream: the pointer to the file where the data will be written.

Return
Type: size_t
Value: On success number of elements which are successfully written
On failure zero (0) if the size or count is 0. Error indicator is set.

fread()
It is used to read data from file. Prototype of the function is:

size_t fread (void* ptr,size_t size,size_t count,FILE* stream)

Parameters
ptr: pointer to memory where the read data will be
stored. size: size of data elements (in byte) to be read.
count: number of data elements to be read.
stream: pointer to the file from which the data will be read.

Return
Type: size_t
Value: On success number of elements which are successfully read.
On failure returns zero (0) if the size or count is 0, Error indicator is set.

Example:

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

int main()

Advanced Computer Programming UNIT 1 Page 38


Vidya Murugendrappa
Assistant Professor

{
FILE *fp;
char c[] = "this is reva university";
char buffer[100];

/* Open file for both reading and writing */


fp = fopen("file.txt", "w+");

/* Write data to the file */


fwrite(c, 1,strlen(c) + 1,fp);

/* Seek to the beginning of the file


*/ fseek(fp, SEEK_SET, 0);

/* Read and display data */


fread(buffer, 1,strlen(c)+1,fp);
printf("%s\n", buffer);
fclose(fp);

return(0);
}

8. ftell()
It is used to get current position of the file pointer. The function prototype is:

long int ftell ( FILE * stream );

Parameters
stream: Pointer to a file.

Return
Type: long integer.
Value: On success value of current position or offset bytes
On failure -1. System specific error no is set

Advanced Computer Programming UNIT 1 Page 39


Vidya Murugendrappa
Assistant Professor

Example:

int main () {
FILE * fp;
long int len;
fp = fopen ("file.txt","r");
if (fp==NULL)
printf ("Error in opening
file"); else {
fseek (fp, 0, SEEK_END);
len=ftell (fp);
}
fclose (fp);
printf ("The file contains %ld characters.\n",len);
}

In this example, file.txt is opened and using fseek(), file pointer is set to the end of the file. Then, ftell()
is used to get the current position, i.e. offset from the beginning of the file.

9. Rewind()
It is used to set the file pointer at the beginning of the file. Function prototype:

void rewind ( FILE * stream );

Parameters
stream: Pointer to a file.

In any stage of the program, if we need to go back to the starting point of the file, we can use rewind()
and send the file pointer as the parameter.
Example:

#include<stdio.h>
int main ()
{
int n;
FILE * fp;
fp = fopen ("file.txt","w+");

Advanced Computer Programming UNIT 1 Page 40


Vidya Murugendrappa
Assistant Professor

if (fp==NULL)
printf ("Error in opening
file"); else {
fputs ("France is my favorite
team",fp); rewind (fp);
fputs("Brazil",fp);
}
fclose (fp);
}

In the above example, first, some string is written in the file. Then rewind() is used to set the file pointer
at the beginning of the file. Then overwrite a word.

10. feof()
It is used to check whether end of file for a stream is set or not. Prototype is:

int feof ( FILE * stream );

Parameters
stream - Pointer to a file.

Return
Type: integer
Value: Non zero value if EOF is set for the stream Zero Otherwise.
by using file pointer as a parameter of feof(), we can check whether end of file has been reached or not.

Example:

Advanced Computer Programming UNIT 1 Page 41


Vidya Murugendrappa
Assistant Professor

#include<stdio.h>
int main()
{
FILE *p;
int c;
fp=fopen(―file.txt‖,‖r‖);
if(fp==NULL)
{
printf(―/nerror in opeing the
file‖); return 0;
}
while(1)
{
c=fgetc(fp);
if (feof(fp))
break;
printf(―%c‖,c);
}
fclose(fp);
return 0;
}

In the above program file.txt file is opened in read mode. Using fgetc() reads a character from the file.

The statement ―feof(fp)‖ checks whether end of file is reached or not. If it has reached it comes out of
the file or else it reads the character from the file.
E. APPLICATIONS OF DATA STRUCTURES
Manipulate hierarchical data.
Make information easy to search (see tree traversal).
Manipulate sorted lists of data.
As a workflow for compositing digital images for visual effects.

Advanced Computer Programming UNIT 1 Page 42


Vidya Murugendrappa
Assistant Professor

F.SOLVING COMPLEX PROBLEMS


#include<stdio.h>

int main()
{
FILE *fp;
char ch;

fp = fopen("INPUT.txt","r") // Open file in Read mode

fclose(fp); // Close File after Reading

return(0);
}
Other problems on structures.

Advanced Computer Programming UNIT 1 Page 43

Das könnte Ihnen auch gefallen