• No results found

POINTERS AND FUNCTIONS

In document C Notes (Page 57-62)

When we pass addresses to a funtion, the parameters receiving the addresses should be pointers. The process of calling a function using pointers to pass the addresses of variable is known as call by reference.

The function which is called by ‘reference’ can change the value of the variable used in the call. Consider the following code:

main() { int x; x = 20; change(&x); printf(“%d\n”, x); }c hange(p) int *p; { p* = *p + 10; }

When the function change() is called, the address of the variable x, not its value, is passed into the function change(). Inside change(), the variable p is declared as a pointer and therefore p is the address of the variable x.

The statement *p = *p +10;

means ‘add 10 to the value stored at the address p’. Since p represents the address of x, the value of x is changed from 20 to 30. Therefore, the output of the program will be 30, not 20. POINTERS AND STRUCTURES

We know that the name of an array stands for the address of its zeroth element. The same thing is true of the names of arrays of structure variables.

Suppose product is an array variable of struct type. The name product represents the address of its zeroth element. Consider the following

declaration: struct inventory { char name[30]; int number; float prince; } product[2], *ptr;

This statement declares product as an array of two elements, each of the type struct

inventory and ptr as a pointer to data objects of the type struct Inventory.

The assignment ptr = product;

would assign the address of the zeroth element of product to ptr. That is, the pointer ptr will now point to product[0]. Its members can be accessed using the following notation.

ptr -> name ptr -> number

ptr -> price

The symbol -> is called the arrow operator and is made up of a minus sign and a greater than sign. Note that ptr -> is simply another way of writing product[0].

When the pointer ptr is incremented by one, it is made to point to the next record, i.e., product[1]. The following for statement will print the values of members of all the elements of product array.

for(ptr = product; ptr < product+2; ptr++)

printf(“%s %d %f\n”, ptr -> name, ptr -> number, ptr -> price); #include<stdio.h> #include<conio.h> void main() { struct book { char name[10]; float price; int pages; };

struct book b1={"basic",130.00,550}; struct book *b2;

clrscr(); b2=&b1;

printf("\n name1 = %s",b1.name); printf("\n price1 = %f",b1.price); printf("\n pages1 = %d",b1.pages); printf("\n name2 = %s",b2->name); printf("\n price2 = %f",b2->price); printf("\n pages2 = %d",b2->pages); getch();

}

Preprocessor

Before a C program is compiled,it is passed through the another proram is called “Pre processor”

The Pre processor works on the source code and creates ‘Expanded Source Code’, which is stored in

‘*.I’.

This expanded source code is sent to compiler for compilation. Pre processor directives begins with a ‘# ‘ symbol.

Some of the pre processor directives are: 1. Macro Expansion.

2. File Inclusion.

MACRO

Macro is a Pre-processor directive which is used to declare symbolic constants. Example: # define UPPER 25

The above statement is called ‘Micro Defination’(Macro), ‘UPPER’ is called ‘ MACRO TEMPLATE’

And 25 is called corresponding ‘macro expansion’. It is customary to use capital letters for micro template. Macro definition never to be terminated by a semicolon. Macro can have arguments.

# define AREA(x) (3.14 *X *X) Main() { Float r1=6.25,a; a=AREA(r1); printf(“Area is =%f”,a); } MACROS Vs Function

In a micro call preprocessor replaces the micro template with it’s micro expansion. In a function call, the control is passed to function along with certain arguments, after performing the talks in that fun a useful value is returned back.

Macros make the program run faster but increase the program size.

Function make the program smaller and compact but takes time to passing the control between functions.

File Inclusion

This directive causes one file to be included in another file. There are two ways to write

# include<filename.h> # include “filename.h” The Build Process

Pre proceesor compiler Assembler Linker

FILE MANAGEMENT IN C:

INTRODUCTION:

A file is a place on the disk where a group of related data is stored. C supports a number of functions that have the ability to perform basic file operations, which include:

1. naming a file, C Source code (PRI.C) Expanded Source code(PRI.I) Assembly code Re locatable Object code

Object code for library

2. opening a file

3. reading data from a file 4. writing data to a file 5. closing a file

The C library uses the following High Level I/O functions: Function name Operation

fopen() Creates a new file for use Opens an existing file for use

fclose() Closes a file which has been opend for use getc() Reads a character from a file

putc() Writes a set of data values to a file fprintf() Writes a set of values from a file fscanf() Reads a set of data values from a file getw() Reads an integer to a file

putw() Writes an integer to a file

fseek() Sets the position to a desired point in the file ftell() Gives the current position in the file

(in terms of bytes from the start)

rewind() Sets the position to the beginning of the file.

Opening a file:

Before we can write information to a file on a disk or read it, we must open the file. Opening a file establishes a link between the program and the operating system. We provide the operating system with the name of the file

and whether we plan to read or write to it. The link between our program and the operating system is a structure called FILE which has been defined in the header file “stdio.h”

(standing for standard input/output header file). When we request the operating system to open a file, we attach a pointer to the Structure

FILE. That is why, we make the following declaration before opening the file,

FILE *fp;

Each file we open will have its own FILE structure. The FILE structure contains information about the file being used, such as its current size, its location in memory etc. More

importantly it contains a character pointer which

points to the character that is about to get read. Now let us understand the following statements,

FILE *fp;

fp = fopen(“pr1.c”, “r”);

fp is a pointer variable, which contains address of the structure FILE ,which has been

defined in the header file “stdio.h”.

fopen() will open a file “pr1.c” in ‘read’ mode, which tells the C compiler that we would be reading the contents of the file. Note that “r” is a string and not a character; hence the double quotes and not single quotes. In

fact, fopen() performs three important tasks when you open the file in “r” mode: 1. Firstly it searches on the disk the file to be opened.

2. If the file is present, it loads the file from the disk into memory.

If the file is absent, fopen() returns a NULL. NULL is a macro defind in “stdio.h” which indicates that you failed to open the file.

3.It sets up a character pointer which points to the first character ofthe memory where the file has been loaded.

Reading from a file:

Once the file has been opened for reading using fopen(), as we have seen the file’s contents are brought into memory and a pointer points to the very first character. The read the file’s contents from memory there exists a

function called fgetc(). This has been used in our sample program through, c = fgetc(fp);

fgetc() reads the character from current pointer position, advances the pointer position so that it now points to the next character, and returns the character that is read, which we collected in the variable c.

We have the used the function fgetc() within an indefinite while loop. There has to be a way to break out of this while. There should be a break whenever we reach the end of the file. End of the file is signified by a special

character, whose ascii value is 26. This character is inserted beyond the last character in the file, when it is created. This character can also be generated from the keyboard by typing ctrl Z. When reading from the file, when fgetc() encounters this special character, instead of returning the character that it has read, it returns the macro EOF. The EOF macro has been defind in the file “stdio.h”.

Trouble in opening a file:

There is a possibility that when we try to open a file using the function fopen(), the file may not be opened. While opening the file in “r” mode, this may happen because the file being opened may not be present on the disk at all. And you obviously cannot read a file which doesn’t exist. Similarly, while opening the file for writing fopen() may fail due to a number of reasons, like, disk space may be insufficient to open a new file, or the disk may be write protected and so on.

#include “stdio.h” main() { FILE *fp; fp = fopen(“pri.c”, “r”); if(fp == NULL) {

puts(“Cannot open file”); exit();

}

}

Closing the file:

When we have finished reading from the file, we need to close it. This is done using the function fclose() through the statement,

fclose(fp);

File opening modes:

A file can be opened in one of several modes. The tasks performed byfopen() when a file is opened in each of these modes are also mentioned. “r” Searces file. If the file exists, loads it into memory and sets up a pointer which points to the first character in it. If the file does’t exist it returns

NULL.

Operations possible - reading from the file.

“w” Searches file. If the file exits, its contents are overwritten. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open

file.

Operations possible - writing to a file.

“a” Searches file. If the file exists, loads it into memory and sets up a pointerwhich points to the first character in it. If the file doesn’t exist, a new file

is created. Returns NULL, if uanble to open file.

Operations possible - appending new contents at the end of file.

“r+” Serches file. If the file exists, loads it into memory and sets up a pointer which points to the first character in it If file doesn’t exist it returns

NULL.

Operations possible - reading existing contents, writing new contents, modifying existing contents of the file.

“w+” Serches file. If the file exists, its contents are destroyed. If the file doesn’t exists a new file is created. Returns NULL, if uanble to open

file.

Operation possible - writing new contents, reading them back and modifying existing contents of the file.

“a+” Searches file. If the file exists, loads it into memory and sets up a pointer which points to the first character in it. If the file doen’t exists, a new file is created. Returns NULL, if unable to open file.

Operations possible - reading existing contents, appending new contents to end of file. Cannot modify existing contents.

In document C Notes (Page 57-62)

Related documents