Download as pdf or txt
Download as pdf or txt
You are on page 1of 28

Fundamental of Computer

Programming
Lab – 10
Waqas Khan
Content
• Pointer
• Pointer arithmetic
• Function pass value by reference
• File Manipulation
Pointers
• A pointer is a variable whose value is the address of another variable,
i.e., direct address of the memory location. Like any variable or
constant, you must declare a pointer before using it to store any
variable address. The general form of a pointer variable declaration is
• type *var-name;
• Here, type is the pointer's base type; it must be a valid C data type and var-name is the
name of the pointer variable. The asterisk * used to declare a pointer is the same
asterisk used for multiplication. However, in this statement the asterisk is being used to
designate a variable as a pointer.
How to Use Pointers?
• There are a few important operations, which we will do with the help
of pointers very frequently.
• We define a pointer variable
• Assign the address of a variable to a pointer
• Finally access the value at the address available in the pointer variable
• This is done by using unary operator * that returns the value of the variable located at
the address specified by its operand. The following example makes use of these
operations
Example
#include <stdio.h>

int main () {

int var = 20; /* actual variable declaration */


int *ip; /* pointer variable declaration */

ip = &var; /* store address of var in pointer variable*/

printf("Address of var variable: %x\n", &var );

/* address stored in pointer variable */


printf("Address stored in ip variable: %x\n", ip );

/* access the value using the pointer */


printf("Value of *ip variable: %d\n", *ip );

return 0;
}
Pointer arithmetic
• A pointer in c is an address, which is a numeric value. Therefore, you
can perform arithmetic operations on a pointer just as you can on a
numeric value. There are four arithmetic operators that can be used
on pointers: ++, --, +, and –
• Incrementing a Pointer
• We prefer using a pointer in our program instead of an array because the variable
pointer can be incremented, unlike the array name which cannot be incremented
because it is a constant pointer. The following program increments the variable pointer
to access each succeeding element of the array
• Decrementing a Pointer
• The same considerations apply to decrementing a pointer, which decreases its value by
the number of bytes of its data type as shown below
Pointer arithmetic Cont.
//Decrementing pointers
#include <stdio.h>

const int MAX = 3;

int main () {

int var[] = {10, 100, 200};


int i, *ptr;

/* let us have array address in pointer */


ptr = &var[MAX-1];

for ( i = MAX; i > 0; i--) {

printf("Address of var[%d] = %x\n", i-1, ptr );


printf("Value of var[%d] = %d\n", i-1, *ptr );

/* move to the previous location */


ptr--;
}

return 0;
}
Pointer arithmetic Cont.
//Incrementing pointers
#include <stdio.h>

const int MAX = 3;

int main () {

int var[] = {10, 100, 200};


int i, *ptr;

/* let us have array address in pointer */


ptr = var;

for ( i = 0; i < MAX; i++) {

printf("Address of var[%d] = %x\n", i, ptr );


printf("Value of var[%d] = %d\n", i, *ptr );

/* move to the next location */


ptr++;
}

return 0;
}
Function pass value by reference
• The call by reference method of passing arguments to a function
copies the address of an argument into the formal parameter. Inside
the function, the address is used to access the actual argument used
in the call. It means the changes made to the parameter affect the
passed argument.
• To pass a value by reference, argument pointers are passed to the
functions just like any other value
Example
#include <stdio.h>

int main () {

/* local variable definition */


int a = 100;
int b = 200;

printf("Before swap, value of a : %d\n", a );


printf("Before swap, value of b : %d\n", b );

/* calling a function to swap the values */


swap(&a, &b);

printf("After swap, value of a : %d\n", a );


printf("After swap, value of b : %d\n", b );

return 0;
}
void swap(int *x, int *y) {

int temp;

temp = *x; /* save the value of x */


*x = *y; /* put y into x */
*y = temp; /* put temp into y */

return;
}
File Manipulation
• In programming, we may require some specific input data to be
generated several numbers of times. Sometimes, it is not enough to
only display the data on the console. The data to be displayed may be
very large, and only a limited amount of data can be displayed on the
console, and since the memory is volatile, it is impossible to recover
the programmatically generated data again and again. However, if we
need to do so, we may store it onto the local file system which is
volatile and can be accessed every time. Here, comes the need of file
handling in C.
File Manipulation Cont.
• File handling in C enables us to create, update, read, and delete the
files stored on the local file system through our C program. The
following operations can be performed on a file.
• Creation of the new file
• Opening an existing file
• Reading from the file
• Writing to the file
• Deleting the file
File Manipulation Cont.
No. Function Description

1 fopen() opens new or existing file

2 fprintf() write data into the file

3 fscanf() reads data from the file

4 fputc() writes a character into the file

5 fgetc() reads a character from file

6 fclose() closes the file

7 fseek() sets the file pointer to given position

8 fputw() writes an integer to file

9 fgetw() reads an integer from file

10 ftell() returns current position

11 rewind() sets the file pointer to the beginning of the file


Opening File: fopen()
• We must open a file before it can be read, write, or update. The
fopen() function is used to open a file. The syntax of the fopen() is
given below.
• FILE *fopen( const char * filename, const char * mode );
• The fopen() function accepts two parameters:
• The file name (string). If the file is stored at some specific location, then we
must mention the path at which the file is stored. For example, a file name
can be like "c://some_folder/some_file.ext".
• The mode in which the file is to be opened. It is a string.
fOpen() cammands
Mode Description

r opens a text file in read mode

w opens a text file in write mode

a opens a text file in append mode

r+ opens a text file in read and write mode

w+ opens a text file in read and write mode

a+ opens a text file in read and write mode


fopen() Cont.
• The fopen function works in the following way.
• Firstly, It searches the file to be opened.
• Then, it loads the file from the disk and place it into the buffer. The
buffer is used to provide efficiency for the read operations.
• It sets up a character pointer which points to the first character of the
file.
Example

#include<stdio.h>
void main( )
{
FILE *fp ;
char ch ;
fp = fopen("file_handle.c","r") ;
while ( 1 )
{
ch = fgetc ( fp ) ;
if ( ch == EOF )
break ;
printf("%c",ch) ;
}
fclose (fp ) ;
}
Closing File: fclose()
• The fclose() function is used to close a file. The file must be closed
after performing all the operations on it. The syntax of fclose()
function is given below:
• int fclose( FILE *fp );
• C fprintf() and fscanf()
• C fputc() and fgetc()
• C fputs() and fgets()
• C fseek()
Writing File : fprintf() function
• The fprintf() function is used to write set of characters into file. It
sends formatted output to a stream.
• int fprintf(FILE *stream, const char *format [, argument, ...])

#include <stdio.h>
int main()
{
FILE *fp;
fp = fopen("file.txt", "w"); //opening file
fprintf(fp, "Hello file by fprintf...\n"); //writing data into file
fclose(fp); //closing file
return 0;
}
Reading File : fscanf() function
• The fscanf() function is used to read set of characters from file. It
reads a word from the file and returns EOF at the end of file.
• int fscanf(FILE *stream, const char *format [, argument, ...])

#include <stdio.h>
int main()
{
FILE *fp;
char buff[255]; //creating char array to store data of file
fp = fopen("file.txt", "r");
while (fscanf(fp, "%s", buff) != EOF)
{
printf("%s ", buff);
}
fclose(fp);
return 0;
}
Writing File : fputc() function
• The fputc() function is used to write a single character into file. It
outputs a character to a stream.
• int fputc(int c, FILE *stream)
#include <stdio.h>
int main()
{
FILE *fp;
fp = fopen("file1.txt", "w"); //opening file
fputc('a', fp); //writing single character into file
fclose(fp); //closing file
return 0;
}
Reading File : fgetc() function
• The fgetc() function returns a single character from the file. It gets a
character from the stream. It returns EOF at the end of file.
• int fgetc(FILE *stream)

#include <stdio.h>

int main()
{
FILE *fp;
char c;
fp = fopen("lab10-11.txt", "r");

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


{
printf("%c", c);
}
fclose(fp);
return 0;
}
Writing File : fputs() function
• The fputs() function writes a line of characters into file. It outputs
string to a stream.
• int fputs(const char *s, FILE *stream)

#include <stdio.h>
int main()
{
FILE *fp;

fp = fopen("myfile2.txt", "w");
fputs("hello c programming", fp);

fclose(fp);
return 0;
}
Reading File : fgets() function
• The fgets() function reads a line of characters from file. It gets string
from a stream.
• char* fgets(char *s, int n, FILE *stream)

#include <stdio.h>
int main()
{
FILE *fp;
char text[300];

fp = fopen("myfile2.txt", "r");
printf("%s", fgets(text, 200, fp));

fclose(fp);
return 0;
}
C fseek() function
• The fseek() function is used to set the file pointer to the specified offset. It is used to
write data into file at desired location.
• int fseek(FILE *stream, long int offset, int whence)

#include <stdio.h>
int main()
{
FILE *fp;

fp = fopen("myfile.txt", "w+");
fputs("This is javatpoint", fp);

fseek(fp, 7, SEEK_SET);
fputs("sonoo jaiswal", fp);
fclose(fp);
return 0;
}
FOR MORE STUDIES
https://www.geeksforgeeks.org/multidimensional-arrays-c-cpp/
https://www.tutorialspoint.com/cprogramming/c_pointers.htm
LET US C (BOOK)
Tasks
• Write a C program to find the max of an integral data set. The program will ask
the user to input the number of data values in the set and each value. The
program prints on screen a pointer that points to the max value
• Given the string "A string." Print on one line the letter on the index 0, the pointer
position and the letter t. undate the pointer to pointer +2. Then, in another line
print the pointer and the letters r and g of the string (using the pointer).
• Create the file with extension dot c (*.c) and write the right angle triangle
program in c language. After that execute that file and print the results.
• Example: write the following logic to print following right angle triangle in c file.
*
**
**
*. *
* *
*. *
*****
Any Question
You can ask any question related to Lab.

You might also like