0% found this document useful (0 votes)
24 views75 pages

POP Unit 5

research

Uploaded by

rottenpotato404
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)
24 views75 pages

POP Unit 5

research

Uploaded by

rottenpotato404
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/ 75

PRINCIPLES OF PROGRAMMING

IN C
22CS2ESPOP - UNIT 5
Prof. SNEHA S BAGALKOT
Assistant Professor, Dept. of CSE
UNIT – 5: Pointers and Files

▪Pointers: Introduction to Pointers


▪Declaring Pointer Variables
▪Pointer Expressions and Pointer Arithmetic
▪Passing Arguments to Functions using Pointers
▪Example Programs.
Pointers
▪ A pointer is a variable which stores the address of another
variable.
▪ A pointer is a derived data type in ‘C’.
▪ Pointers can be used to access and manipulate data stored in
memory.
Introduction
• Pointer variable is denoted by * symbol
Ex: *p
• Address of a variable is denoted by & symbol
Ex: &a //address of a
• Address of a can be stored in p
Ex: int a = 10;
int *p;
p = &a;
Advantages of Pointers

▪ Pointers are more efficient in handling arrays and data tables.


▪ Pointers can be used to return multiple values from a function.
▪ Pointers allow ‘C’ to support dynamic memory management.
▪ Pointers provide an efficient tool for manipulating dynamic
data structures such as stack, queue etc.
Declaring Pointer variable

DataType *Pointer_var_name;
Declaring Pointer variable
DataType *Pointer_var_name;

Example:
int *ptr;
int Var;

Var=10;
ptr=&Var;
Example Program
#include <stdio.h>
main()
{
int a, *p;

a=38;
p=&a;

}
Example Program
#include <stdio.h>
main()
{
int a, *p;

a=38;
p=&a;

printf("&a=%x a=%d\n", &a, a);


printf("p=%x *p=%d\n", p,*p);

}
Example Program
#include <stdio.h>
main()
{
int a, *p;

a=38;
p=&a;

printf("&a=%x a=%d\n", &a, a); Output:


printf("p=%x *p=%d\n", p, *p); &a=fb6f9c a=38
p=fb6f9c *p=38

}
Find the output of following program
#include <stdio.h>
main()
{
int a, *p;
float b, *q;

a=38;
p=&a;
printf("&a=%x a=%d\n", &a, a);
printf("p=%x *p=%d\n", p,*p);

b=47.5;
q=&b;
printf("&b=%x b=%f\n", &b, b);
printf("q=%x *q=%f\n", q,*q);
}
Find the output of following program
#include <stdio.h>
main()
{
int a, *p;
float b, *q;

a=38;
p=&a;
printf("&a=%x a=%d\n", &a, a);
printf("p=%x *p=%d\n", p,*p);

Output:
b=47.5;
&a=a0e98050 a=38
q=&b; p=a0e98050 *p=38
printf("&b=%x b=%f\n", &b, b); &b=a0e98054 b=47.50
printf("q=%x *q=%f\n", q, *q); q=a0e98054 *q=47.50

}
Example
Initial int a, *p; p = &a; int a = 100, b = 200, *p, *q;
1. a = 100; p = &a;
2. a = a + 3 q = &b;
3. *p = 200;
4. a = *p + *p; 6. a = *p + *q;
5. a = *p * 4; 7. b = *p * *q;
Example
Example Program

Output:
Pointers of different Datatypes

Output:
Pointer Expressions and Pointer Arithmetic
Write a program to find area and perimeter of printf ( "Enter radius of a circle " ) ;
a circle using pointers scanf ( "%d", &radius ) ;

#include<stdio.h> areaperi ( radius, &area, &perimeter ) ;


void areaperi ( int r, float *a, float *p )
{ printf ( "Area = %f", area ) ;
*a = 3.14 * r * r ; printf ( "Perimeter = %f", perimeter ) ;
*p = 2 * 3.14 * r ; }
}
Output
void main( )
{
int radius ;
float area, perimeter ;
Write a C program to test whether a number is positive,
negative ,or equal to zero
Program to add two numbers using pointers
#include <stdio.h>
void main()
{
int num1, num2, sum;
int *ptr1, *ptr2;

ptr1 = &num1; // ptr1 stores the address of num1


ptr2 = &num2; // ptr2 stores the address of num2

printf("Enter any two numbers: ");


scanf("%d%d", ptr1, ptr2);

sum = *ptr1 + *ptr2;

printf("Sum = %d", sum);


}
Arithmetic Operations on Pointer variables
Example Program
#include <stdio.h>
main()
{
int u=20, v=5;
int *p, *q;

p=&u;
q=&v;

}
Arithmetic Operations on Pointer variables
Example Program
#include <stdio.h>
main()
{
int u=20, v=5;
int *p, *q;

p=&u;
q=&v;

printf("%d %d\n", *p + *q, u + v);


}
Arithmetic Operations on Pointer variables

Example Program
#include <stdio.h>
main()
{
int u=20, v=5;
int *p, *q;

p=&u;
q=&v; Output:
25 25
printf("%d %d\n", *p + *q, u + v);
}
Arithmetic Operations on Pointer variables
Example Program
#include <stdio.h>
main()
{
int u=20, v=5;
int *p, *q;

p=&u;
q=&v;

printf("%d %d\n", *p + *q, u + v);


printf(“%d\n”,*p*u);
}
Arithmetic Operations on Pointer variables
Example Program
#include <stdio.h>
main()
{
int u=20, v=5;
int *p, *q;

p=&u;
q=&v; Output:
25 25
printf("%d %d\n", *p + *q, u + v); 400
printf(“%d\n”,*p * u);
}
Pointer Increments and Scale Factor

When a pointer is incremented, its value is increased by the size


of the datatype that it points to. This length is called the “scale
factor”.
Scale Factor
Example Program
#include <stdio.h>
main()
{
char *a, b;

a=&b;

printf("%u %u %u\n", &b, a, a+1);


}
Scale Factor
Example Program
#include <stdio.h>
main()
{
char *a, b;
float *x, y;

a=&b;
x=&y;

printf("%u %u %u\n", &b, a, a+1);


printf("%u %u %u\n", &y, x, x+1);
}
Scale Factor
Example Program
#include <stdio.h>
main()
{
char *a, b;
float *x, y;
Output: (Example Address)
200 200 201
a=&b; 300 300 304
x=&y;

printf("%u %u %u\n", &b, a, a+1);


printf("%u %u %u\n", &y, x, x+1);
}
Question
What is the output of the following C code?

char *ptr;
char mystring[10] = "abcdefg";
ptr = mystring;
ptr += 5;
printf("%s", ptr);

a) fg
b) efg
c) defg
d) cdefg
e) bcdefg
Question
What is the output of the following C code?

char *ptr;
char mystring[10] = "abcdefg";
ptr = mystring;
ptr += 5;
printf("%s", ptr);

a) fg
b) efg
c) defg
d) cdefg
e) bcdefg

Answer: a
Passing Arguments to Functions
using Pointers
Ex: Swapping two values-call by reference
UNIT – 5: Pointers and Files

▪Files: Introduction to Files


▪Using Files in C
▪Read Data from Files
▪Writing Data to Files
▪Example Programs.
Introduction to Files
• A file is a collection of data stored on a secondary storage device like
hard disk.
• Broadly speaking, a file is basically used because real-life applications
involve large amounts of data and in such applications the console-
oriented I/O operations pose two major problems:
➢First, it becomes cumbersome and time-consuming to handle huge
amount of data through terminals.
➢Second, when doing I/O terminal, the entire data is lost when either
the program is terminated or computer is turned off. Therefore, it
becomes necessary to store data on a permanent storage device(eg:
hard disk) and read whenever required, without destroying the data.
Introduction to Files:
• Why files in C?

• Till now, we have been reading the input from the keyboard. If we have to
process large amount of data its cumbersome to type the whole thing.

• Hence we can use the input as the data stored in a file.

• We can also write the output to a file instead in the standard output since the
output might be lost.

• Streams in C:

• In C, standard streams are termed as pre-connected input and output channels


between a text terminal and the program.
The three standard streams in C are:
• Standard input(stdin)
• Standard output(stdout)
• Standard error(stderr)
Streams in C
• Standard Input(stdin): standard input or the stream from which the program receives its
data. The program requests transfer of data using read operation.

• Standard Output(stdout): standard output is the stream where a program writes its
output data. The program requests data transfer using the write operation.

• Standard Error(stderr): it is basically an output stream used by programs to report error


messages or diagnostics. It is stream independent of standard output and can be
redirected separately.

• A stream is linked to a file using an open operation and dissociated from a file using a
close operation.
Buffer associated with file streams
• When a stream linked to a file is created, a buffer is automatically created and associated with the
stream.
• A buffer is nothing but a block of memory that is used for temporary storage of data that has to
be read from or written to a file.
• Buffers are needed because disk drives are block-oriented devices as they can operate efficiently
when data has to be read/written in blocks of certain size.
• The buffer acts as an interface between the stream and the disk hardware. When the program
has to write data to the stream, it is saved in the buffer till it is full. Then the entire contents of
the buffer are written to the disk as a block.

Program Buffer Disk


Program
writes data Data from the
to buffer buffer is
written to the
disk file
Contd…
• Similarly, when reading the data from a disk file, the data is read as a block from
the file and written into the buffer.

• The program reads data from the buffer. The creation and operation of the buffer
is automatically handled by the operating system.

• C provides some functions for buffer manipulation.

• The data resides in the buffer until the buffer is flushed or written to a file.
Types of files
ASCII TEXT FILES:

• A text file is a stream of characters that can be sequentially processed by a


computer in forward direction.

• Because text files only process characters they read and write one character at a
time.

• A line in a text file is not a string in C. Hence it is not terminated by a NULL


character.

• A file is terminated by a special character called the end-of-file(EOF)


Types of files
BINARY FILES:

• A binary file may contain any type of data , encoded in binary form for computer
storage and processing purposes.

• A binary file doesn’t require any special processing of data and each byte of data
is transferred to or from the disk unprocessed.

• Text files can be processed sequentially while binary files can be either processed
sequentially or randomly depending on the need of the application.
Using files in C:
To use files in C, we must follow the steps given below;

• Declare a file pointer variable

• Open a file

• Process the file

• Close the file


DECLARING A FILE POINTER VARIABLE:
• In order to access a particular file from the disk we use a file pointer variable that points
to a structure FILE (defined in stdio.h)

• The file pointer will then be used in all file operations in the program.

• SYNTAX:

FILE *file_pointer_name;

▪ For example:
FILE *fp; // fp is declared as a file pointer
OPENING A FILE:
• A file should be opened before a data could be read from it or written to it.

• In order to open a file in a computer we use fopen() function: the prototype of


fopen() is given below:

FILE *fopen(const char *file_name, const char *mode);

• File name could be any name , “file.txt”, “hello.c” or a path name like
“/home/user/file1.txt” or a file in D directory “D:\BMS\Notes\file2.txt”

• Mode “r” “w” “a” “r+” “w+” “a+”, rb, wb


OPENING A FILE:
• fopen() returns pointer-to-structure on successful creation of file, returns NULL
otherwise.

• Mode: “r” open text file for reading. If The file doesn’t exist throws an error.

• “w”: open a text file for writing. If a file doesn't exist, it creates it and over-writes
the contents.

• “a”: append data to a file. If File doesn’t exists it is created.

• Similarly, “rb”, ”wb”, ”ab” for binary files.


File Name
• Every file on the disk has a name associated with it.

• Windows have restrictions on usage of certain characters in the


filenames, i.e., characters such as /,\,:,*,?,”,<,> and ! Cannot be a part
of a filename.

Example: D:\\BE\\Student.DAT
FILE MODE
CLOSING A FILE:
• To close a open file , the fclose() function is used which disconnects a file pointer
from a file.

• Prototype of the function fclose() is:

int fclose(FILE *fp);

• Returns 0 if function was successful

• Non-zero value is returned if an error occurred.


Write a C program to display if a file is successfully created or not.
READING DATA FROM FILES :

• C provides set of functions to read data from a file ,They are:


fscanf( ) , fgets( ) , fgetc( ) , fread( )
WRITING DATA TO FILES :
•C provides set of functions to write data to a file ,They are:

fprintf( ) , fputs( ) , fputc( ) , fwrite( )


PART B: LAB PROGRAM 6

Demonstrate how to read data from the keyboard,


write it to a file called BMSCE, again read
the same data from the BMSCE file, and display it
on the screen/console.
Output:
Usage of fscanf( ) in files
•fscanf(): is similar to the scanf( ) function, except that the first
argument of fscanf( ) specifies a stream from which to read(stdin or
fp), whereas scanf() can only read from standard input(stdin).
• Syntax
int fscanf(FILE *stream, const char *format,..);
• fscanf() is used to read data from the stream and store them
accordingly.
• Format specifiers of scanf and fscanf is similar
#include<stdio.h> fscanf(stdin, "%s %d", name, &roll_no);

int main() printf("name=%s, roll_no=%d\n \n", name, roll_no);


{ //reading name and rollno from another file(input.txt)
FILE *fp;
fscanf(fp,"%s %d", name, &roll_no);
char name[20]; int roll_no;
printf("name=%s, roll_no=%d", name, roll_no);
fp = fopen("input.txt", "r");
fclose(fp);
if(fp==NULL)
return 0;
{

printf("the file couldn't be opened\n"); }

exit(0);

} //reading name and rollno from keyboard

printf("enter the name and rollno\n");


USAGE OF fprintf( )
This is used to write the formatted output to a stream.

Syntax:

int fprintf(FILE * stream, const char * format ,…) ;

The function writes data that is formatted as specified by the format


argument.

The parameter format in fprintf() is a C string that contains the text that
has to be written
• The prototype of the format tag can be given as
• %[flags][width][.precision][length]specifier
• Each format specifier must begin with a % sign. The % sign is followed
by
• Flags:
• Width:
• Precision:
• Length:
• Specifier:
Example
#include<stdio.h> if(fp == NULL)
int main() {
{ printf("the file couldn't be opened\n");
FILE *fp; exit(0);
char name[20]; }
int age; fprintf(fp,"%s %d", name, age);
printf("enter your name and age\n"); fclose(fp);
scanf("%s\t%d", name, &age); return 0;
fp=fopen("input.txt", "w"); }
Usage of fgets( )
•fgets( ): The function fgets( ) stands for file get string. This function is used to get
a string from a stream.

•Syntax:

char *fgets(char *str, int size, FILE *stream);

•This function reads at most one less than the number of characters specified by
size from the given stream and stores them in the string str.
Usage of fgets( )
•It is terminated when it encounters either a newline character, EOF or
any other error.
•When all the characters are read without any error, a ‘\0’ character is
appended to the end of the string.
• gets( ) and fgets( ) are almost the same but gets( ) has infinite size and
a stream of stdin.
•On successful completion, fgets() will return str.
#include<stdio.h>
fgets(str, 10, fp);
int main()
{ puts(str);
FILE *fp; fclose(fp);
char str[15];
return 0;
int roll_no;
}
fp = fopen("input.txt", "r");
if(fp == NULL) If input.txt contains bmscecollege
{
Output bmscecoll is displayed on
printf("the file couldn't be opened\n");
monitor
exit(0);
}
USAGE OF fputs( )

• Opposite of fgets is fputs( ).

•The fputs() is used to write a line to a file.

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

• It writes the string pointed to by str to the stream pointed to by stream.

• On successful completion, fputs( ) returns 0 ,on error it returns EOF.


#include<stdio.h> //data read from the file input.txt and stored in array- str

int main() fgets(str, 10, fp);


{ puts(str);
FILE *fp; //data stored in a string-str is written to the file input1.txt
FILE *fp1; fp1=fopen("bms.txt", "w");
char str[26];
fputs(str, fp1);
int roll_no;
fclose(fp1);
fp=fopen(“input.txt", "r");
fclose(fp);
if(fp == NULL)
return 0;
{
}
printf("the file couldn't be opened\n");
If input.txt contain bmscecollege
exit(0);
Output is bmscecoll is stored in bms.txt
}
USAGE OF fgetc( );(both fgetc( ) and fputc( ))

• fgetc() is used to read the contents from the file character by character.
fgetc(file_pointer);
int main() //write the data to file input.txt
{ for(i=0; i<length; i++)
{
FILE *fp;
fputc(data[i], fp);
char ch; }
char data[25] = "BMS COLLEGE"; fclose(fp);
int length = strlen(data); //read the data using fgetc()
int i; fp = fopen("input.txt", "r");
fp = fopen("input.txt", "w");
if(fp == NULL)
{
printf("the file couldn't be opened\n");
exit(0);
}
while(!feof (fp) )
{
ch = fgetc(fp);
printf("%c", ch);
}
fclose(fp);
return 0;
}
USAGE OF fputc( ):
•this is opposite of fgetc().

• This function write a character to the stream.

• Syntax:

int fputc(int c, FILE *stream);

•It will write the byte specified by C( converted to an unsigned char) to the output
stream pointed to by stream.

•On successful completion, fputc() will return the value it has written.

•In case of error, the function will return EOF.


#include<stdio.h> if(fp==NULL)
{
int main() printf("the file couldn't be opened\n");
exit(0);
{
}
FILE *fp; for(i=0; i<length; i++)
{
char data[25]="BMS COLLEGE"; fputc(data[i], fp);
}
int length =strlen(data);
fclose(fp);
int i; return 0;
}
fp = fopen("input.txt", "w");
USAGE OF fread( )
• The fread() function is used to read data from a file

• Syntax:

int fread(void *str, size_t size, size_t num, FILE *stream);

•The fread() function reads num number of objects and places them into the array
pointed to by str.

•The data is read from the given input stream.

•Upon successful completion, fread() returns the number of bytes successfully


read.
USAGE OF fwrite( )
Example program:

Demonstrate how to read data from the keyboard, write it to a file


called INPUT, again read the same data from the INPUT file, and display
it on the screen/console.
#include <stdio.h>
int main() fclose(fp);
{ /* Close the file INPUT */
FILE *fp; printf("\nData Output\n\n");
char c; /* Reopen the file INPUT */

printf("Data read from the keyboard:Input\n\n"); fp = fopen("INPUT.dat","r");


/* Read a character from INPUT*/
/* Open the file INPUT */
while((c=fgetc(fp)) != EOF)
fp = fopen("INPUT.dat", "a");
/* Display a character on screen */
/* Get a character from keyboard */
printf("%c",c);
while((c=getchar()) != EOF)
/* Close the file INPUT */
/* Write a character to INPUT */ fclose(fp);
fputc(c,fp); }
THANK
YOU

You might also like